41

I want to match all strings except the string "ABC". Example:

 "A"     --> Match
 "F"     --> Match
 "AABC"  --> Match
 "ABCC"  --> Match
 "CBA"   --> Match
 "ABC"   --> No match

I tried with [^ABC], but it ignores "CBA" (and others).

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
PT Huynh
  • 595
  • 1
  • 5
  • 12
  • 2
    I believe this has been discussed lengthily at http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word. – wombat Apr 06 '13 at 15:57
  • 1
    @wombat, that other question is about rejecting a string that *contains* a certain substring. This one is about the special case of a string that consists entirely of `ABC`. `AABC` and `ABCC` are okay. – Alan Moore Apr 06 '13 at 16:29

3 Answers3

58
^(?!ABC$).*

matches all strings except ABC.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
3

Judging by you examples, I think you mean "all strings except those containing the word ABC".

Try this:

^(?!.*\bABC\b)
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Invert the Match with GNU Grep

You can simply invert the match using word boundaries and the specific string you want to reject. For example:

$ egrep --invert-match '\bABC\b' /tmp/corpus 
"A"     --> Match
"F"     --> Match
"AABC"  --> Match
"ABCC"  --> Match
"CBA"   --> Match

This works perfectly on your provided corpus. Your mileage may vary for other (or more complicated) use cases.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • 2
    Your demonstration works perfectly, however I have no something like "invert-match" in my case. Thanks! – PT Huynh Apr 07 '13 at 01:40