如果找到多个匹配,则正则表达式失败

时间:2014-11-12 17:26:22

标签: regex sqlclr

采取以下正则表达式:

P[0-9]{6}(\s|\.|,)

这是为了检查字符串中前面带有“P”的6位数字 - 大部分都可以正常工作。

问题是,如果找到多个匹配,我们需要失败 - 这可能吗?

即。使以下屏幕截图中的文本4失败,但仍然保持所有其他人失败/通过,如下所示:

enter image description here

(此RegEx正在SQL .net CLR中执行)

2 个答案:

答案 0 :(得分:5)

如果此工具使用的正则表达式引擎确实是.NET引擎,那么您可以使用

^(?:(?!P[0-9]{6}[\s.,]).)*P[0-9]{6}[\s.,](?:(?!P[0-9]{6}[\s.,]).)*$

如果它是原生SQL引擎,那么您无法使用单个正则表达式匹配,因为这些引擎不支持外观断言。

<强>解释

^                         # Start of string
(?:                       # Start of group which matches...
 (?!P[0-9]{6}[\s.,])      # unless it's the start of Pnnnnnn...
 .                        # any character
)*                        # any number of times
P[0-9]{6}[\s.,]           # Now match Pnnnnnn exactly once
(?:(?!P[0-9]{6}[\s.,]).)* # Match anything but Pnnnnnn
$                         # until the end of the string

测试live on regex101.com

答案 1 :(得分:0)

或使用此模式

^(?!(.*P[0-9]{6}[\s.,]){2})(.*P[0-9]{6}[\s.,].*)$

Demo
基本上检查模式是否存在且不重复两次。

^               Start of string
(?!             Negative Look-Ahead
  (             Capturing Group \1
    .           Any character except line break
    *           (zero or more)(greedy)
    P           "P"
    [0-9]           Character Class [0-9]
    {6}         (repeated {6} times)
    [\s.,]          Character Class [\s.,]
  )             End of Capturing Group \1
  {2}           (repeated {2} times)
)               End of Negative Look-Ahead
(               Capturing Group \2
  .             Any character except line break
  *             (zero or more)(greedy)
  P             "P"
  [0-9]         Character Class [0-9]
  {6}           (repeated {6} times)
  [\s.,]            Character Class [\s.,]
  .             Any character except line break
  *             (zero or more)(greedy)
)               End of Capturing Group \2
$               End of string