Why is regex negation required?

There are so many questions about SO in regex-negation .

I'm not sure I understand why people feel the need to cancel regex. Why not use something like grep -v , which only shows results that don't match the regular expression?


 $ 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 
+2
source share
3 answers

Perhaps because grep is not the only place where regular expressions are used? It works in this simple scenario ... and in fact in many others, where you can simply say "does not match this regular expression" ... but ... well, what if you need to cancel only part of the regular expression? β€œMatches this, but doesn't match it," how would you do it? You cannot simply deny it all.

+9
source

Are you right that there is no need to deny the whole regex, but do you see the value in the negation of the subpattern in the larger template?

Here is a simple example: split the line into runs. In Java, it's just split on (?<=(.))(?!\1) .

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

Regular expression:

  • (?<=(.)) - find and write the character in \1
  • (?!\1) - see and cancel the match on \1

Related Questions

All of these questions use negative statements:

+2
source

One instance where I remember it was in the Apache configuration. In Apache, there is a way to redirect to a different URI if the current request matches some PCRE regular expression, but it does (or at least was when I needed it) cannot redirect if the current request does not match the regular expression.

Fortunately, I succeeded in Google (in fact, I'm not sure that Google already exists and hellip;) for regexp-negation regex. But it probably took me some time, and if StackOverflow existed then it would be much easier.

0
source

Source: https://habr.com/ru/post/1314751/


All Articles