[英]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: 换一种说法:
^
) ^
) $
) $
) 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. 你的第一个模式正在传递,因为它实际上被解释为
^pattern1
或pattern2$
,因此它部分匹配输入而不是完全匹配。 The breakdown for this pattern is: 这种模式的细分是:
^
upto the pipe symbol) ^
到管道符号) $
) $
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.