Reputation: 137
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
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:
(?<!X)Y
is a negative lookbehind which matches a Y not preceeded by an XY(?!X)
is a negative lookahead which matches a Y not followed by an Xworking 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
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:
(?:^|\s)
- Matches either the beginning of the line, or a single space character(IF|ELSE)
- Matches one of your keywords(?:$|\s)
- Matches either the end of the line, or a single space character.Upvotes: 3