如何检查命名捕获组是否存在? [英] How to check if a named capture group exists?

查看:46
本文介绍了如何检查命名捕获组是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my regex the pattern is something like this:

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

所以我想知道< somename> 是否存在.如果这是一个正常的捕获组,我可以检查一下捕获组是否大于没有该捕获组的捕获组的数量,但是我在这里没有选择.

So I would like to know if <somename> exists. If it was a normal capture group, I could just check if the capture groups are greater than the number of groups without that/those capture group(s), but I don't have the option here.

有人可以帮我找到解决方法吗?我不需要它高效,它只是用于一次性程序的排序,因此我不介意是否需要花费一些时间.它不会用于公共代码.

Could anyone help me find a way round this? I don't need it to be efficient, it's just for a one-time program that's used for sorting, so I don't mind if it takes a bit to run. It's not going to be for public code.

推荐答案

根据文档:

如果groupname不是集合中捕获组的名称,或者,如果groupname是尚未被捕获的捕获组的名称在输入字符串中匹配时,该方法返回一个Group对象,该对象的Group.Success属性为false,并且其Group.Value属性为String.Empty.

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;

这篇关于如何检查命名捕获组是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆