正则表达式为2项,但有一个排除

时间:2014-04-16 16:46:03

标签: regex regex-negation

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

DateTime.Now
or 
Date.Now

但不能有文字" SystemDateTime"在同一条线上。

我从这个(DateTime\.Now|Date\.Now)开始,但现在我被困在哪里放置" SystemDateTime"

3 个答案:

答案 0 :(得分:0)

使用它。假设您没有使用/s修饰符(或DOTALL)在点(.

下使用换行符
(?!.*SystemDateTime)(DateTime\.Now|Date\.Now)

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

答案 1 :(得分:0)

您可以像这样使用negative lookahead

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

答案 2 :(得分:0)

/(?!.*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»