我有以下带有正则表达式的字符串示例,我试图匹配它:
Regex:
^\d{3}( [0-9a-fA-F]{2}){3}
要匹配的字符串:010 00 00 00
我的问题是这样的 - 正则表达式匹配并捕获 1 组 - 最终00
在字符串的末尾。但是,我希望它能够匹配所有三个00
组在最后。为什么这不起作用?当然括号应该意味着它们都同等匹配吗?
我知道我可以分别输入这三个组,但这只是较长字符串的简短摘录,因此这会很痛苦。我希望这能提供一个更优雅的解决方案,但似乎我的理解有些缺乏!
Thanks!
由于捕获组上有量词,因此您只能看到上次迭代的捕获。不过,幸运的是,.NET(与其他实现不同)提供了一种从以下位置检索捕获的机制:all迭代,通过CaptureCollection 类。从链接的文档:
如果将量词应用于捕获组,则 CaptureCollection 将为每个捕获的子字符串包含一个 Capture 对象,并且 Group 对象仅提供有关最后捕获的子字符串的信息。
链接文档中提供了示例:
// Match a sentence with a pattern that has a quantifier that
// applies to the entire group.
pattern = @"(\b\w+\W{1,2})+";
match = Regex.Match(input, pattern);
Console.WriteLine("Pattern: " + pattern);
Console.WriteLine("Match: " + match.Value);
Console.WriteLine(" Match.Captures: {0}", match.Captures.Count);
for (int ctr = 0; ctr < match.Captures.Count; ctr++)
Console.WriteLine(" {0}: '{1}'", ctr, match.Captures[ctr].Value);
Console.WriteLine(" Match.Groups: {0}", match.Groups.Count);
for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
{
Console.WriteLine(" Group {0}: '{1}'", groupCtr, match.Groups[groupCtr].Value);
Console.WriteLine(" Group({0}).Captures: {1}",
groupCtr, match.Groups[groupCtr].Captures.Count);
for (int captureCtr = 0; captureCtr < match.Groups[groupCtr].Captures.Count; captureCtr++)
Console.WriteLine(" Capture {0}: '{1}'", captureCtr, match.Groups[groupCtr].Captures[captureCtr].Value);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)