Javascript Regex for a partial string match only
14,387
Solution 1
You want to use a non-word boundary \B
here.
/\Batta|atta\B/
Solution 2
sp00m almost got it right
^(atta.+|.+atta|.+atta.+)$
If whitespace is not allowed you could write
^(atta[\S]+|[\S]+atta|[\S]+atta[\S]+)$
Author by
maurya8888
Updated on June 05, 2022Comments
-
maurya8888 almost 2 years
I need to write a JavaScript RegEx that matches only the partial strings in a word.
For example if I search using the string 'atta'
it should return
true for khatta true for attari true for navrattan false for atta
I am not able to figure how to get this done using one RegEx. Thanks!
-
sp00m almost 10 yearsOr even
^(atta.+|.+atta.*)$
;) -
chris97ong almost 10 yearsHmm...so
atta
gives false butatta
gives true. -
Per Hornshøj-Schierbeck almost 10 yearsI think this is a much cleaner answer than mine
-
MaxArt almost 10 yearsGood one. I may add that for
test
the capturing group is useless and memory consuming. I wonder if!/\batta\b/.test(string)
isn't any faster... -
Lee Kowalkowski almost 10 years@MaxArt would that not also match "foobar"? If you're really worried about capturing groups, use a non-capturing group:
/(?:\Batta|atta\B)/
-
maurya8888 almost 10 yearsI believe
!/\batta\b/.test(string)
will return true for "this too". I need a partial match at least. -
MaxArt almost 10 yearsYep,
/\batta\b/
would match strings that also don't contain "atta" at all - I guess OP doesn't want that. @LeeKowalkowski There's no need to have groups either, in this case. -
Lee Kowalkowski almost 10 years@MaxArt oh how right you are! I seemed to have thought the brackets were always required for
|
. I will edit my answer (and a few regexes I have lying around ha ha)