Using regex in javascript, let's say I want to match foo
. But I only want to match it if bar
doesn't come immediately before or after it.
Matches foo
foo
foo bar
bar foo
string foo
stringfoo
foo. string
Does NOT Match foo
barfoo
foobar
Using regex in javascript, let's say I want to match foo
. But I only want to match it if bar
doesn't come immediately before or after it.
Matches foo
foo
foo bar
bar foo
string foo
stringfoo
foo. string
Does NOT Match foo
barfoo
foobar
You can use negative lookbehinds and negative lookaheads:
(?<!bar)foo(?!bar)
(?<!x)y
. This expression will match y
if it is not immediately preceded by x
.y(?!x)
. This expression will match y
if it is not immediately followed by x
.As others have said, the simplest regex to do this in most languages is with a negative look-behind and a negative look-ahead:
(?<!bar)foo(?!bar)
However, Javascript does not support look-behinds in regular expressions. Instead, you can mimic the behaviour of a look-behind with a second look-ahead:
(?:(?!bar).{3}|^.{0,2})(foo)(?!bar)
I have placed foo
in a capture group, in case you actually want to use the value of this match in your real code; if you only care about whether the regex matches, rather than what the regex matches, then you can replace (foo)
with just foo
(no brackets).
The trick is in this part of the regex: (?!bar).{3}|^.{0,2}
. This is saying "either 3 characters that are not bar
, or fewer than 3 characters" - which will effectively achieve the same result as a look-behind.