Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following list of regular expressions

C#
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)
        }


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 ??
Posted

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


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


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.
 
Share this answer
 
If you mean "how do I get teh match data by name?", that's easy:
C#
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:
C#
Regex regex = new Regex(@"(?<hour>\d\d?):(?<minute>\d\d)\s?(?<meridiem>(a|p).?m)", RegexOptions.IgnoreCase);
string[] names = regex.GetGroupNames();
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.
 
Share this answer
 
Comments
rohith naik 22-Oct-14 8:56am    
Thanks !
OriginalGriff 22-Oct-14 10:01am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900