0

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?

1
  • FYI, added detailed explanation to the pattern. Commented Apr 21, 2014 at 11:43

3 Answers 3

2

Maybe you want to use \b word boundaries:

(\bGRE\b)

Here is the explanation

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

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.