gpt4 book ai didi

c# - 如何检查命名捕获组是否存在?

转载 作者:IT王子 更新时间:2023-10-29 04:34:18 25 4
gpt4 key购买 nike

在我的正则表达式中,模式是这样的:

@"Something\(\d+, ""(.+)""(, .{1,5}, \d+, (?<somename>\d+)?\),"

所以我想知道是否<somename>存在。如果它是一个普通的捕获组,我可以只检查捕获组是否大于没有那个/那些捕获组的组数,但我没有这里的选项。

谁能帮我找到解决这个问题的方法?我不需要它来提高效率,它只是用于排序的一次性程序,所以我不介意运行起来是否需要一点时间。它不会用于公共(public)代码。

最佳答案

根据documentation :

If groupname is not the name of a capturing group in the collection, or if groupname is the name of a capturing group that has not been matched in the input string, the method returns a Group object whose Group.Success property is false and whose Group.Value property is String.Empty.

var regex = new Regex(@"Something\(\d+, ""(.+)""(, .{1,5}, \d+, (?<somename>\d+)?\),");
var match = regex.Match(input);
var group = match.Groups["somename"];
bool exists = group.Success;

关于c# - 如何检查命名捕获组是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389340/

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