-1

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
jkupczak
  • 2,891
  • 8
  • 33
  • 55

2 Answers2

2

You can use negative lookbehinds and negative lookaheads:

(?<!bar)foo(?!bar)
  • Negative lookbehinds follow the syntax (?<!x)y. This expression will match y if it is not immediately preceded by x.
  • Negative lookaheads follow the syntax y(?!x). This expression will match y if it is not immediately followed by x.
  • Unfortunately, I need this to work in Javascript. And based on the comments above I believe negative lookbehinds will not work. I suppose I'm out of luck? – jkupczak Aug 03 '17 at 21:00
1

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)

Demo

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)

Demo

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.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77