Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is negation of a regex needed?

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
like image 349
Lazer Avatar asked Jan 29 '26 16:01

Lazer


2 Answers

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.

like image 118
mpen Avatar answered Jan 31 '26 06:01

mpen


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:

  • How to negate the whole regex?
  • Regular Expression :match string containing only non repeating words
  • using regular expression in Java - match all permutations of ABCDEFG (e.g. letters in any order)
  • Need Regex for to match special situations - a few more examples
like image 26
polygenelubricants Avatar answered Jan 31 '26 05:01

polygenelubricants



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!