Regular Expression Opposite

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

提交回复
热议问题