Jay Cui
Jay Cui

Reputation: 137

Regular expression match specific key words

I am trying to use regexp to match some specific key words.

For those codes as below, I'd like to only match those IFs at first and second line, which have no prefix and postfix. The regexp I am using now is \b(IF|ELSE)\b, and it will give me all the IFs back.

IF A > B THEN STOP
   IF B < C THEN STOP
LOL.IF
IF.LOL
IF.ELSE

Thanks for any help in advance. And I am using http://regexr.com/ for test. Need to work with JS.

Upvotes: 1

Views: 675

Answers (2)

Andreas Linden
Andreas Linden

Reputation: 12721

you can do it with lookaround (lookahead + lookbehind). this is what you really want as it explicitly matches what you are searching. you don't want to check for other characters like string start or whitespaces around the match but exactly match "IF or ELSE not surrounded by dots"

/(?<!\.)(IF|ELSE)(?!\.)/g

explanation:

  • use the g-flag to find all occurrences
  • (?<!X)Y is a negative lookbehind which matches a Y not preceeded by an X
  • Y(?!X) is a negative lookahead which matches a Y not followed by an X

working example: https://regex101.com/r/oS2dZ6/1

PS: if you don't have to write regex for JS better use a tool which supports the posix standard like regex101.com

Upvotes: 1

nickb
nickb

Reputation: 59699

I'm guessing this is what you're looking for, assuming you've added the m flag for multiline:

(?:^|\s)(IF|ELSE)(?:$|\s)

It's comprised of three groups:

  1. (?:^|\s) - Matches either the beginning of the line, or a single space character
  2. (IF|ELSE) - Matches one of your keywords
  3. (?:$|\s) - Matches either the end of the line, or a single space character.

Regexr

Upvotes: 3

Related Questions