views:

170

answers:

3

There are so many questions on regex-negation here on SO.

I am not sure I understand why people feel the need to negate a regex. Why not use something like grep -v that shows only the results that do not match the regex?


$ ls
april  august  december  february  january  july  june  march  may  november  october  september
$ ls | grep ber
december
november
october
september
$ ls | grep -v ber
april
august
february
january
july
june
march
may
+8  A: 

Probably because grep isn't the only place that regexes are used? It works in this simple scenario... and actually in many others where you can just say "doesn't match this regex"... but... well, what if you need to negate only part of a regex? "Matches this, but doesn't match this" how would you do that? You can't just negate the whole thing.

Mark
A: 
Jörg W Mittag
+2  A: 

You're right that there's no need to negate a whole regex, but certainly you see value in negating a subpattern within a larger pattern?

Here's a simple example: split a string into runs. In Java, this is simply a split on (?<=(.))(?!\1).

System.out.println(java.util.Arrays.toString(
    "aaaabbbccdeeefg".split("(?<=(.))(?!\\1)")
)); // prints "[aaaa, bbb, cc, d, eee, f, g]"

The regex is:

  • (?<=(.)) - lookbehind and capture a character into \1
  • (?!\1) - lookahead and negate a match on \1

Related questions

All of these questions uses negative assertions:

polygenelubricants