Match.Groups[].Value 返回重复值
输入是 55
,我的正则表达式是 ^(5{2})$
。所以理想情况下(至少对我来说)这应该返回每个以 5 开头并以 5 结尾的字符串,对吗?
但是,当我的 C# 如下所示时:
Match match = Regex.Match(input, String.Format(@"{0}", regex));
string outcome = null;
if (match.Success)
{
for (int i = 0; i < match.Groups.Count; i++)
{
outcome += match.Groups[i].Value;
}
}
为什么我的字符串 outcome
返回 5555 而不是 55?
当我从正则表达式中删除括号时,它工作得很好。
The input is 55
, and my regex is ^(5{2})$
. So ideally (at least to me) this should return every string that starts with a 5 and ends with a 5 right?
But when my c# is like the following:
Match match = Regex.Match(input, String.Format(@"{0}", regex));
string outcome = null;
if (match.Success)
{
for (int i = 0; i < match.Groups.Count; i++)
{
outcome += match.Groups[i].Value;
}
}
Why does my string outcome
returns 5555 instead of 55?
When I remove the brackets from the regex it works perfectly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
match.Groups
中的第一项包含正则表达式选取的整个匹配项。第二项是括号中捕获的内容。由于正则表达式和输入本质上是相同的字符串
"55"
,因此您会得到两个相同的匹配项:一个匹配整个输入,另一个匹配捕获组(括号)。将两者连接起来,您将得到
"55" + "55"
,即"5555"
。The first item in
match.Groups
contains the entire match that's picked up by your regex. The second item is what's captured in the brackets.Since the regex and input are essentially the same string
"55"
, you get two identical matches: one for the entire input matched, and one for the capture group (the brackets).Both of these are concatenated and you get
"55" + "55"
, which is"5555"
.