0

To match all characters except vowels, we can use [^aeiou].

I wonder

  • how to match all strings other than a particular one? For example, I want to match a string which is not dog. So cat, sky, and mike will all be matches.

  • how to match all strings other than a few strings, or other than a regular expression? For example, I want to match a string which is not c.t. So sky and mike will all be matches, but cat and cut will not be matches.

Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • I would say whoever downvote or close are those who don't understand regex, and don't like others to learn about it. – Tim Jun 08 '14 at 02:31

1 Answers1

3

1. How to match all strings other than a particular one

^(?!your_string$).*$

2. How to match all strings other than a few strings

^(?!(?:string1|string2|string3)$).*$

How does that work?

  1. The idea is to use a negative lookahead (?! to check that the string does not consists solely of the string(s) to avoid. If the negative lookahead (which is an assertion) succeeds, the .*$ matches everything to the end of the string.
  2. Note the use of the ^ anchor at the beginning to ensure we are positioned at the beginning of the string.
  3. Note the $ anchor inside the negative lookahead to ensure that we are excluding your_string if it is indeed the whole string, but that we do not exclude your_string and more

Reference

  1. Mastering Lookahead and Lookbehind
  2. Negative Lookaheads
Community
  • 1
  • 1
zx81
  • 41,100
  • 9
  • 89
  • 105
  • Thanks. I appreciate your reply, despite that some people can't understand my questions for some mysterious reasons. – Tim Jun 08 '14 at 02:31
  • @Tim I am surprised that there are so many people trying to close your questions. There are old questions on the same topics with tons of upvotes, but many of the answers at the time were far less detailed. – zx81 Jun 08 '14 at 02:32