4

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!

0

2 Answers 2

9

You want to use a non-word boundary \B here.

/\Batta|atta\B/
Sign up to request clarification or add additional context in comments.

6 Comments

I think this is a much cleaner answer than mine
Good 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...
@MaxArt would that not also match "foobar"? If you're really worried about capturing groups, use a non-capturing group: /(?:\Batta|atta\B)/
I believe !/\batta\b/.test(string) will return true for "this too". I need a partial match at least.
Yep, /\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.
|
2

sp00m almost got it right

^(atta.+|.+atta|.+atta.+)$

Fiddle.

If whitespace is not allowed you could write

^(atta[\S]+|[\S]+atta|[\S]+atta[\S]+)$

2 Comments

Or even ^(atta.+|.+atta.*)$ ;)
Hmm...so atta gives false but atta gives true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.