简体   繁体   English

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

[英]Why do parentheses make my regex not match?

This matches: 匹配:

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*)?)*$"));

But when I add parentheses after the ^ and before the $ it doesn't 但是当我在^之后和$之前添加括号时它没有

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*)?)*)$"));

Can anyone tell me why? 谁能告诉我为什么?

Update: 更新:

I see now that my original expression was wrong. 我现在看到我的原始表达是错误的。 I should have had my \\d\\d|\\d\\d\\d\\d portions enclosed in a non-capturing group like this: 我应该将我的\\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*)?)*$

Which could also be written as 这也可以写成

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

This would allow me to add additional parentheses as needed without changing the behavior. 这将允许我根据需要添加额外的括号而不改变行为。 Thanks. 谢谢。

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

The second pattern with the parentheses makes the ^ and $ metacharacters apply to the entire pattern, which means the entire string must match the pattern. 带括号的第二个模式使^$元字符适用于整个模式,这意味着整个字符串必须与模式匹配。 In other words: 换一种说法:

  • Match beginning of string ( ^ ) 匹配字符串的开头( ^
  • Your pattern 你的模式
  • Match end of string ( $ ) 匹配字符串结尾( $

Your first pattern was passing because it is actually being interpreted as ^pattern1 or pattern2$ , thus it was partially matching the input rather than doing so entirely. 你的第一个模式正在传递,因为它实际上被解释为^pattern1pattern2$ ,因此它部分匹配输入而不是完全匹配。 The breakdown for this pattern is: 这种模式的细分是:

  • Match beginning of string and first alternate (from ^ upto the pipe symbol) 匹配字符串的开头和第一个备用(从^到管道符号)
  • Or match the second alternate and the end of the string (after the pipe symbol till $ ) 或者匹配第二个备用字符串和字符串结尾(在管道符号之后直到$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM