为什么括号使我的正则表达式不匹配

本文关键字:正则表达式 不匹配 我的 为什么 | 更新日期: 2023-09-27 17:49:54

匹配:

Console.WriteLine(Regex.IsMatch("15, 17-19", @"^'s*'d'd|'d'd'd'd's*(?:-'s*'d'd|'d'd'd'd's*)?(?:,'s*'d'd|'d'd'd'd's*(?:-'s*'d'd|'d'd'd'd's*)?)*$"));

但是当我在^后面和$前面加括号时它不会

Console.WriteLine(Regex.IsMatch("15, 17-19", @"^('s*'d'd|'d'd'd'd's*(?:-'s*'d'd|'d'd'd'd's*)?(?:,'s*'d'd|'d'd'd'd's*(?:-'s*'d'd|'d'd'd'd's*)?)*)$"));

谁能告诉我为什么?

更新:

我现在知道我原来的表达是错误的。我应该把我的'd'd|'d'd'd'd部分包含在一个非捕获组中,像这样:
^'s*(?:'d'd|'d'd'd'd)'s*(?:-'s*(?:'d'd|'d'd'd'd)'s*)?(?:,'s*(?:'d'd|'d'd'd'd)'s*(?:-'s*(?:'d'd|'d'd'd'd)'s*)?)*$

也可以写成

^'s*(?:'d{2}|'d{4})'s*(?:-'s*(?:'d{2}|'d{4})'s*)?(?:,'s*(?:'d{2}|'d{4})'s*(?:-'s*(?:'d{2}|'d{4})'s*)?)*$

这允许我在不改变行为的情况下根据需要添加额外的括号。谢谢。

为什么括号使我的正则表达式不匹配

第二个带括号的模式使^$元字符应用于整个模式,这意味着整个字符串必须匹配该模式。换句话说:

  • 匹配字符串(^)开头
  • 你的模式
  • 匹配字符串($)的结尾

你的第一个模式是通过的,因为它实际上被解释为^pattern1pattern2$,因此它部分匹配输入,而不是完全这样做。该模式的细分如下:

  • 匹配字符串的开头和第一个替代(从^到管道符号)
  • 匹配第二个替代字符串和字符串的末尾(在管道符号之后直到$)

表达式中有管道-当您添加括号时,它会改变表达式的工作方式。