40

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
  • 313,408
  • 56
  • 485
  • 544
PT Huynh
  • 583
  • 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

57
^(?!ABC$).*

matches all strings except ABC.

Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
3

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

Try this:

^(?!.*\bABC\b)
Bohemian
  • 389,931
  • 88
  • 552
  • 692
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
  • 76,463
  • 14
  • 137
  • 188
  • 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