如何在正则表达式中获取命名组 [英] How do I get the named groups in a regex

查看:72
本文介绍了如何在正则表达式中获取命名组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式列表



I have the following list of regular expressions

private List<Regex> _timeExtractionRegex = new List<Regex>()
        {
            new Regex(@"(?<hour>\d\d?):(?<minute>\d\d)\s?(?<meridiem>(a|p).?m)" , RegexOptions.IgnoreCase),
            new Regex(@"(?<hour>\d\d?)\s?(?<meridiem>(a|p).?m)" , RegexOptions.IgnoreCase),
            new Regex(@"(?<hour>\d\d?):(?<minute>\d\d)" , RegexOptions.IgnoreCase)
        }





第一个命名为群组 - 小时,分钟和meridiem。

第二个命名组 - 小时和meridiem。



问题这是从不同的来源发送给我的。如何获取命名捕获组的所有名称?



The first one has named groups - hour, minute and meridiem.
The second one has named groups - hour and meridiem.

The problem is that this is being sent to me from a different source. How do i get all the names of the named capture groups ??

推荐答案

引用:

如何获取指定捕获组的所有名称?

How do i get all the names of the named capture groups ??







int name;
var groupNames = _timeExtractionRegex.SelectMany(x=>x.GetGroupNames())
     .Where(n=>!int.TryParse(n, out name))
	 .Distinct().ToList();





请注意,GetGroupNames方法将返回未命名的组作为数字,如0,1,2等等,我已经添加了近似过滤掉这些组名的位置。



Note that GetGroupNames method will return unnamed groups as numerical numbers like 0,1,2 so on, I have added where close to filter out those group names.


如果你的意思是如何通过名字获得匹配数据?,那很简单:

If you mean "how do I get teh match data by name?", that's easy:
string inputText = "12:45";
Regex regex = new Regex(@"(?<hour>\d\d?):(?<minute>\d\d)\s?(?<meridiem>(a|p).?m)", RegexOptions.IgnoreCase);
Match m = regex.Match(inputText);
string hour = m.Groups["hour"].Value;

如果你的意思是如何获得群组的鬃毛?,这也很简单:

If you mean "how do I get the manes of the groups?", that's pretty simple too:

Regex regex = new Regex(@"(?<hour>\d\d?):(?<minute>\d\d)\s?(?<meridiem>(a|p).?m)", RegexOptions.IgnoreCase);
string[] names = regex.GetGroupNames();

请注意,对于表达式中的两个未命名组,GroupNames数组将包含0和1,以及命名的组的名称。

Do note that the GroupNames array will contain "0" and "1" for the two unnamed groups in your expression, as well as the names of the named ones.


这篇关于如何在正则表达式中获取命名组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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