Regular Expression Opposite

前端 未结 7 946
悲&欢浪女
悲&欢浪女 2020-11-28 07:55

Is it possible to write a regex that returns the converse of a desired result? Regexes are usually inclusive - finding matches. I want to be able to transform a regex into

相关标签:
7条回答
  • 2020-11-28 08:20

    The reason your inverted regex isn't working is because of the '^' inside the negative lookahead:

    /^((?!^[ab].).)*$/
          ^            # WRONG
    

    Maybe it's different in vim, but in every regex flavor I'm familiar with, the caret matches the beginning of the string (or the beginning of a line in multiline mode). But I think that was just a typo in the blog entry.

    You also need to take into account the semantics of the regex tool you're using. For example, in Perl, this is true:

    "abc" =~ /[ab]./
    

    But in Java, this isn't:

    "abc".matches("[ab].")
    

    That's because the regex passed to the matches() method is implicitly anchored at both ends (i.e., /^[ab].$/).

    Taking the more common, Perl semantics, /[ab]./ means the target string contains a sequence consisting of an 'a' or 'b' followed by at least one (non-line separator) character. In other words, at ANY point, the condition is TRUE. The inverse of that statement is, at EVERY point the condition is FALSE. That means, before you consume each character, you perform a negative lookahead to confirm that the character isn't the beginning of a matching sequence:

    (?![ab].).
    

    And you have to examine every character, so the regex has to be anchored at both ends:

    /^(?:(?![ab].).)*$/
    

    That's the general idea, but I don't think it's possible to invert every regex--not when the original regexes can include positive and negative lookarounds, reluctant and possessive quantifiers, and who-knows-what.

    0 讨论(0)
提交回复
热议问题