gpt4 book ai didi

c# - 正则表达式匹配多个组

转载 作者:太空狗 更新时间:2023-10-29 23:24:35 24 4
gpt4 key购买 nike

我有以下我试图匹配的带有正则表达式的字符串示例:

正则表达式:^\d{3}( [0-9a-fA-F]{2}){3}

要匹配的字符串:010 00 00 00

我的问题是 - 正则表达式匹配并捕获 1 组 - 字符串末尾的最后一个 00。但是,我希望它在末尾匹配所有三个 00 组。为什么这不起作用?括号里应该是均等匹配的意思吧?

我知道我可以单独输入这三个组,但这只是一个更长字符串的简短摘录,所以这会很痛苦。我希望这会提供一个更优雅的解决方案,但似乎我的理解有些欠缺!

谢谢!

最佳答案

因为您在捕获组上有一个量词,所以您只能看到上次迭代的捕获。幸运的是,.NET(与其他实现不同)提供了一种机制,通过 the CaptureCollection class所有 迭代中检索捕获。 .来自链接文档:

If a quantifier is applied to a capturing group, the CaptureCollection includes one Capture object for each captured substring, and the Group object provides information only about the last captured substring.

以及链接文档中提供的示例:

  // 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);
}

关于c# - 正则表达式匹配多个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13689259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com