【问题标题】:RegEx to tell if a string is not a specific string正则表达式来判断一个字符串是否不是一个特定的字符串
【发布时间】:2012-03-13 14:22:03
【问题描述】:

假设我想匹配除一个之外的所有字符串:“ABC” 我该怎么做?

我在 asp.net mvc 3 中需要 regular expression model validation

【问题讨论】:

    标签: regex regex-negation


    【解决方案1】:

    通常你会喜欢

    (?!ABC)
    

    例如:

    ^(?!ABC$).*
    

    所有不是ABC的字符串

    分解的意思是:

    ^ beginning of the string
    (?!ABC$) not ABC followed by end-of-string
    .* all the characters of the string (not necessary to terminate it with $ because it is an eager quantifier)
    

    从技术上讲,您可以做类似的事情

    ^.*(?<!^ABC)$
    

    分解的意思

    ^ beginning of the string
    .* all the characters of the string 
    (?<!^ABC) last three characters captured aren't beginning-of-the-string and ABC 
    $ end of the string (necessary otherwise the Regex could capture `AB` of `ABC` and be successfull)
    

    使用负面的看法,但阅读(和写作)更复杂

    啊,显然不是所有的正则表达式实现都实现了它们 :-) .NET 实现了。

    【讨论】:

      【解决方案2】:

      在不知道您使用什么语言的情况下很难明确地回答这个问题,因为正则表达式有很多种风格,但您可以通过否定前瞻来做到这一点。

      https://stackoverflow.com/a/164419/1112402

      【讨论】:

      • 我需要这个在 asp.net mvc 3 中进行正则表达式模型验证。
      【解决方案3】:
      (?!.*ABC)^.*$
      

      这将排除所有包含 ABC 的字符串。

      【讨论】:

        【解决方案4】:

        希望这会有所帮助:

        ^(?!^ABC$).*$
        

        使用这个表达式,您将获得从 (^) 开始到 ($) 结束之间所有可能的字符串 (.*),但那些恰好是 ^ABC$.

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-02
          • 1970-01-01
          相关资源
          最近更新 更多