Regex question: Retrieve group names in code?

  • Thread starter Jeff Johnson [MVP: VB]
  • Start date
J

Jeff Johnson [MVP: VB]

[Pardon the crossposting, but it seemed appropriate given the lack of a
dedicated group]

Is there any way to retrieve the name of a capture group from the classes
provided in the RegularExpressions namespace? GroupCollection implements
ICollection and IEnumerable, not IDictionary, so there doesn't seem to be
any means to retrieve key values.

While I realize this isn't generally needed in a production scenario (you
normally KNOW what your groups are called), it is quite necessary if you're
building a general regular expression evaluation app (like The Regulator or
Regex Workbench).

In case I'm not being clear, consider the following example (error-trapping
and most braces omited for brevity--and in two languages to justify the
crosspost):

[You have a form with three text boxes, txtRegex, txtString, and txtOutput.
The user puts "(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{4})" into
txtRegex and "Today's date is 12/1/2004. Where has the year gone?" in
txtString and clicks the Evaluate button.]

-------VB--------
Private Sub btnEval_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnEval.Click
Dim rgx As Regex, m As Match
rgx = New Regex(txtRegex.Text)
m = rgx.Match(txtString.Text)
If m.Success Then
For Each g As Group In m.Groups
If g.Index <> 0 Then
' This is what I'd LIKE to do
txtOutput.AppendText("Group '" & g.Name & "' = '" & g.Value
& "'" & Environment.NewLine)
End If
Next
End If
End Sub
--------------------

--------C#--------
private void btnEval_Click(object sender, System.EventArgs e)
{
Regex rgx = new Regex(txtRegex.Text);
Match m = rgx.Match(txtString.Text);
if (m.Success)
foreach (Group g in m.Groups)
if (g.Index != 0)
// This is what I'd LIKE to do
txtOutput.AppendText("Group '" + g.Name + "' = '" + g.Value
+ "'\r\n");
}
--------------------

I would then like the output text box to contain:

Group 'month' = '12'
Group 'day' = '1'
Group 'year' = '2004'

(And pardon my C# if I made any syntax or style mistakes.)
 
L

Lucas Tam

I would then like the output text box to contain:

Group 'month' = '12'
Group 'day' = '1'
Group 'year' = '2004'

You can use the method: GroupNameFromNumber to retreive the group name.


To get the GroupNumber, you can just iterate through the group collection.
 
J

Jeff Johnson [MVP: VB]

You can use the method: GroupNameFromNumber to retreive the group name.

AAAGGGHHH!! It's in the Regex class! I didn't look at that at all. I was
concentrating on...well, basically every OTHER class. Many thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top