Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of captured groups in a C# Regex?

Tags:

c#

regex

Is there a way to get the name of a captured group in C#?

string line = "No.123456789  04/09/2009  999"; Regex regex = new Regex(@"(?<number>[\d]{9})  (?<date>[\d]{2}/[\d]{2}/[\d]{4})  (?<code>.*)");  GroupCollection groups = regex.Match(line).Groups;  foreach (Group group in groups) {     Console.WriteLine("Group: {0}, Value: {1}", ???, group.Value); } 

I want to get this result:

 Group: [I don´t know what should go here], Value: 123456789  04/09/2009  999 Group: number, Value: 123456789 Group: date,   Value: 04/09/2009 Group: code,   Value: 999 
like image 913
Luiz Damim Avatar asked Sep 04 '09 19:09

Luiz Damim


People also ask

What is named capture group?

Some regular expression flavors allow named capture groups. Instead of by a numerical index you can refer to these groups by name in subsequent code, i.e. in backreferences, in the replace pattern as well as in the following lines of the program.

How do I reference a capture group in regex?

If your regular expression has named capturing groups, then you should use named backreferences to them in the replacement text. The regex (?' name'group) has one group called “name”. You can reference this group with ${name} in the JGsoft applications, Delphi, .

Can I use named capturing groups?

Mixing named and numbered capturing groups is not recommended because flavors are inconsistent in how the groups are numbered. If a group doesn't need to have a name, make it non-capturing using the (?:group) syntax. In . NET you can make all unnamed groups non-capturing by setting RegexOptions.

What is capturing group in regex Javascript?

A part of a pattern can be enclosed in parentheses (...) . This is called a “capturing group”. That has two effects: It allows to get a part of the match as a separate item in the result array.


1 Answers

Use GetGroupNames to get the list of groups in an expression and then iterate over those, using the names as keys into the groups collection.

For example,

GroupCollection groups = regex.Match(line).Groups;  foreach (string groupName in regex.GetGroupNames()) {     Console.WriteLine(        "Group: {0}, Value: {1}",        groupName,        groups[groupName].Value); } 
like image 153
Jeff Yates Avatar answered Sep 17 '22 19:09

Jeff Yates