Why is negation of a regex needed?

放肆的年华 提交于 2019-12-24 00:58:52

问题


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

回答1:


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.




回答2:


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



回答3:


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

Thankfully, I was able to Google (actually, I'm not sure that Google existed already …) for a regexp-negation regexp. But it sure took me some time, and if StackOverflow had existed back then, it would have been much easier.



来源:https://stackoverflow.com/questions/2890873/why-is-negation-of-a-regex-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!