4

What is the RegEx pattern I should use in order to match a specific word that does not come after another specific word?

For example:

I'm looking for an "abc" that does not come after "xyz", so the following will match:

xxabc

p abc

And the following will not:

xyz abc

Thanks!

Bobulous
  • 12,967
  • 4
  • 37
  • 68
ml123
  • 1,059
  • 2
  • 12
  • 27
  • These answers make use of negative look behind - which is fine, but be aware not all Regex engines support this. JavaScript regex, for example, does not. – vcsjones Dec 29 '13 at 16:56
  • Do you want it to fail matching if `xyz` is immediately before `abc` or _anywhere_ before `abc`? – Jerry Dec 29 '13 at 17:21

2 Answers2

6

The easiest way is a negative lookbehind assertion:

(?<!xyz)(?<!xyz )abc

Your variation in spacing between letter groups, however, suggests that you might see some variation in distance between abc and xyz. If you only want to find abc if it is never preceded by xyz earlier in the string, then you may need something more along the lines of this:

^(?!xyz)*((?!xyz).)*abc

The latter regular expression uses an equivalent of inverse matching rather than a negative lookbehind assertion.

Community
  • 1
  • 1
Justin O Barber
  • 11,291
  • 2
  • 40
  • 45
  • This answer would be worth an upvote just for being the only one to offer a solution that doesn't involve lookbehinds. But I don't see why you need both `(.(?!xyz))*` and `((?!xyz).)*`, especially given that the first one is broken. When you put the dot in front of the lookahead, it doesn't start filtering until the second character. That's why your regex incorrectly matches the string `"xyz abc"`. – Alan Moore Dec 29 '13 at 18:13
  • @Alan Moore, Excellent point. Thanks for catching that. I modified the first parenthetical expression, so that its primary purpose is to catch xyz in the event that xyz immediately precedes abc (without any intervening characters). Thanks. – Justin O Barber Dec 29 '13 at 18:23
0

You need something like this:

(?<!xyz )abc

Regular expression visualization

Debuggex Demo

But syntax will vary, depending on the language you are using. For example, this syntax won't work in JavaScript.

elixenide
  • 44,308
  • 16
  • 74
  • 100