-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
5
  • 1
    (?<!bar)foo(?!bar) if your regex supports look arounds Commented Aug 3, 2017 at 20:07
  • Is it SQL, Go, Google Apps Script, JavaScript, VBA? If not, @anubhava's suggestion will work. Commented Aug 3, 2017 at 20:35
  • Possible duplicate of Python regex negative lookbehind Commented Aug 3, 2017 at 20:52
  • 1
    OP clearly said "in javascript". So negative look-behinds will not work, and an answer in python is not a duplicate. Commented Aug 3, 2017 at 20:53
  • Apologies for the missing info in my original post. I've updated it to call out javascript specifically. Commented Aug 3, 2017 at 21:02

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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.

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.