Regular Expression Opposite

前端 未结 7 945
悲&欢浪女
悲&欢浪女 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:02

    You can also do this (in python) by using re.split, and splitting based on your regular expression, thus returning all the parts that don't match the regex, how to find the converse of a regex

    0 讨论(0)
  • 2020-11-28 08:02

    Java Regexps have an interesting way of doing this (can test here) where you can create a greedy optional match for the string you want, and then match data after it. If the greedy match fails, it's optional so it doesn't matter, if it succeeds, it needs some extra data to match the second expression and so fails.

    It looks counter-intuitive, but works.

    Eg (foo)?+.+ matches bar, foox and xfoo but won't match foo (or an empty string).

    It might be possible in other dialects, but couldn't get it to work myself (they seem more willing to backtrack if the second match fails?)

    0 讨论(0)
  • 2020-11-28 08:03

    You can invert the character set by writing a ^ at the start ([^…]). So the opposite expression of [ab] (match either a or b) is [^ab] (match neither a nor b).

    But the more complex your expression gets, the more complex is the complementary expression too. An example:

    You want to match the literal foo. An expression, that does match anything else but a string that contains foo would have to match either

    1. any string that’s shorter than foo (^.{0,2}$), or
    2. any three characters long string that’s not foo (^([^f]..|f[^o].|fo[^o])$), or
    3. any longer string that does not contain foo.

    All together this may work:

    ^[^fo]*(f+($|[^o]|o($|[^fo]*)))*$
    

    But note: This does only apply to foo.

    0 讨论(0)
  • 2020-11-28 08:05

    In perl you can anti-match with $string !~ /regex/;.

    0 讨论(0)
  • 2020-11-28 08:11

    Couldn't you just check to see if there are no matches? I don't know what language you are using, but how about this pseudocode?

    if (!'Some String'.match(someRegularExpression))
        // do something...
    

    If you can only change the regex, then the one you got from your link should work:

    /^((?!REGULAR_EXPRESSION_HERE).)*$/
    
    0 讨论(0)
  • 2020-11-28 08:11

    With grep, you can use --invert-match or -v.

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