【问题标题】:Regex for 2 items but with one exclusion2 个项目的正则表达式,但有一个排除项
【发布时间】:2014-05-31 16:16:03
【问题描述】:

我正在构建一个 RegEx,它需要查找具有以下任一条件的行:

DateTime.Now
or 
Date.Now

但不能在同一行包含文字“SystemDateTime”。

我从 (DateTime\.Now|Date\.Now) 开始,但现在我不知道在哪里放置“SystemDateTime

【问题讨论】:

    标签: regex regex-negation


    【解决方案1】:

    使用这个。假设您没有使用/s 修饰符(或DOTALL),它在点下使用换行符(.

    (?!.*SystemDateTime)(DateTime\.Now|Date\.Now)
    

    (?!.*SystemDateTime) 表示前面没有SystemDateTime

    【讨论】:

      【解决方案2】:

      你可以像这样使用negative lookahead

      (?!.*SystemDateTime)\bDate(?:Time)?\.Now\b
      

      【讨论】:

        【解决方案3】:
        /(?!.*SystemDateTime)Date(?:Time)?\.Now/
        

        DEMO

        解释:

        Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*SystemDateTime)»
           Match any single character that is not a line break character «.*»
              Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
           Match the characters “SystemDateTime” literally «SystemDateTime»
        Match the characters “Date” literally «Date»
        Match the regular expression below «(?:Time)?»
           Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
           Match the characters “Time” literally «Time»
        Match the character “.” literally «\.»
        Match the characters “Now” literally «Now»
        

        【讨论】:

          猜你喜欢
          • 2012-06-22
          • 2019-10-28
          • 2017-03-13
          • 1970-01-01
          • 2012-12-05
          • 2014-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多