Question

Now, I know I can calculate if a string contains particular substring.Using this:

if(str.indexOf("substr") > -1){
}

Having my substring 'GRE' I want to match for my autocomplete list:

GRE:Math

GRE-Math

But I don't want to match:

CONGRES

and I particularly need to match:

NON-WORD-CHARGRENON-WORD-CHAR and also
GRE

What should be the perfect regex in my case?

Was it helpful?

Solution

Maybe you want to use \b word boundaries:

(\bGRE\b)

Here is the explanation

Demo: http://regex101.com/r/hJ3vL6

OTHER TIPS

MD, if I understood your spec, this simple regex should work for you:

\W?GRE(?!\w)(?:\W\w+)?

But I would prefer something like [:-]?GRE(?!\w)(?:[:-]\w+)? if you are able to specify which non-word characters you are willing to allow (see explanation below).

This will match

GRE
GRE:Math
GRE-Math

but not CONGRES

Ideally though, I would like to replace the \W (non-word character) with a list of allowable characters, for instance [-:] Why? Because \W would match non-word characters you do not want, such as spaces and carriage returns. So what goes in that list is for you to decide.

How does this work?

\W? optionally matches one single non-word character as you specified. Then we match the literal GRE. Then the lookahead (?!\w) asserts that the next character cannot be a word character. Then, optionally, we match a non-word character (as per your spec) followed by any number of word characters.

Depending on where you see this appearing, you could add boundaries.

You can use the regex: /\bGRE\b/g

if(/\bGRE\b/g.test("string")){
  // the string has GRE
}
else{
  // it doesn't have GRE
}

\b means word boundary

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top