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).

2
  • 2
    I believe this has been discussed lengthily at stackoverflow.com/questions/406230/…. Commented Apr 6, 2013 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. Commented Apr 6, 2013 at 16:29

3 Answers 3

58
^(?!ABC$).*

matches all strings except ABC.

Sign up to request clarification or add additional context in comments.

10 Comments

I think he wants all combinations of 'A' 'B' 'C', right? (i.e. in any 3-length string)
@d'alar'cop CBA should be matched according to the examples
but then shouldn't his [^ABC] work? if not, how come?
@d'alar'cop [^ABC] will reject CBA
I also tried with negative but never get it works, because I didn't use an ending position inside. Thanks Tim!
|
3

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

Try this:

^(?!.*\bABC\b)

1 Comment

@Bohemaian: No, I mean "all strings except this specific string 'ABC'"
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.

1 Comment

Your demonstration works perfectly, however I have no something like "invert-match" in my case. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.