gpt4 book ai didi

c# - 正则表达式:如何捕获重复捕获组中的所有迭代

转载 作者:行者123 更新时间:2023-11-30 20:33:52 24 4
gpt4 key购买 nike

我希望这些 C# 行:

var regex = new Regex("A(bC*)*");
var match = regex.Match("AbCCbbCbCCCCbbb");
var groups = match.Groups;

返回类似的东西:

["AbCCbbCbCCCCbbb", "A", "bCC", "b", "bC", "bCCC", "b", "b", "b"]

但它只返回最后捕获的匹配项:

["AbCCbbCbCCCCbbb", "b"]

Here Regex101 还显示以下内容作为警告:

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

我应该如何更改我的正则表达式模式?

最佳答案

如果您还想捕获 A,只需将其用括号括起来:new Regex("(A)(bC*)*")。查看regex demo .

enter image description here

然后,收集你在 CaptureCollection 中得到的所有值:

var regex = new Regex("(A)(bC*)*");
var match = regex.Matches("AbCCbbCbCCCCbbb")
.Cast<Match>()
.SelectMany(x => x.Groups.Cast<Group>()
.SelectMany(v => v.Captures
.Cast<Capture>()
.Select(t => t.Value)
)
)
.ToList();
foreach (var s in match)
Console.WriteLine(s);

参见 C# demo

关于c# - 正则表达式:如何捕获重复捕获组中的所有迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39845994/

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