0

I found many questions regarding this on SO, but they always assume that the word is at the beginning or end.

Assuming the word is cat, I don't want to match any of these:

  1. cat
  2. hellocat
  3. catfood
  4. nocatthere

A common idea seems to be something like this:

^([^c]*|c([^a]|$|a([^t]|$)))*

The regex works like this:

  1. match anything except a c [^c]*

  2. or, if you have matched a c, then match only something other than a, or the end of the word([^a]|$

  3. or, if you have matched a ca, then match only something other than t, or the end of the word ([^t]|$)

The examples work correctly, they aren't matched.

But the regex can be confused:

The following examples match:

  1. ccat
  2. cacat
lhk
  • 27,458
  • 30
  • 122
  • 201
  • 1
    What is the regex flavor? See [Regular expression to match line that doesn't contain a word?](http://stackoverflow.com/questions/406230/regular-expression-to-match-line-that-doesnt-contain-a-word). There is an answer even for cases when a lookahead is not available. – Wiktor Stribiżew Apr 06 '16 at 15:00
  • Or, see [Hades32's answer](http://stackoverflow.com/a/7286050/3832970) – Wiktor Stribiżew Apr 06 '16 at 15:09
  • Like Wiktor said, a negative lookahead is what you are looking for most likely. Lookaheads are not available in all languages. They ensure that the characters following the required text match without including the required text in the match. For instance, a Ruby example for "cat" would be `(?!c).*` where "at" is returned from the match. – polskais1 Apr 06 '16 at 15:13

0 Answers0