Search code examples
javascriptregexnegative-lookbehind

Javascript Regex; find 'x', but not if preceded by 'y'


Something like the word 'pie' not preceded by the word 'pizza'. I'm fairly new to regexes, and this problem has been causing me trouble.

If you could provide an answer using JavaScript regex syntax, i'd be that much more thankful.

Edit: I could probably replicate the functionality by searching individually for the strings 'pizza pie' and 'pie' in two separate regexes, and only count the string indexes that appear in the second find but not the first. It's a convoluted solution that's not quite as fast, but can be easily multithreaded so I suppose it's okay.


Solution

  • This is called negative lookbehind, and a regex for "x not preceded by y" would look like (?<!y)x. Unfortunately, JavaScript doesn't support negative lookbehind, but check out this question for alternatives to it.