Regex - Getting the name of a capture?

  • Thread starter Thread starter Lee Chapman
  • Start date Start date
L

Lee Chapman

I am thinking about using a regex to parse a string of data. My regex is of
the form

(?'m1'string1)|(?'m2'string2)|(?'m3'string3) etc.

I can get a match through Match.Captures[0], but I can't seem to find anyway
to get the 'mx' information from the Capture object. Is this possible? I
don't want to have to test each Match.Groups["mx"].Success for all possible
mx's... How can I get the capture name from the match?

Thanks,
- Lee
 
Thanks, but what if I don't know the name of the group?

e.g. If I apply the regex

(?'GroupA'[0-9])|(?'GroupB'[A-Z])

to the string

5

then I'll get a match with one group; if I apply it to the string

G

then I will also get a match with one group.

So in both cases I can access the group through Groups[1] - but this doesn't
give me the information I'm after - in each case I want to know *which*
group was matched. I can test Groups["GroupA"].Success and
Groups["GroupB"].Success - i.e. test each possibility in turn - but isn't
there a way of just asking which group was matched directly?

- Lee

Dino Chiesa said:
The capture name is an indexer into the Groups collection on the Match.

eg rather than
Match.Captures[0]
you can do
Match.Groups["m1"]

It is an alternative to using integer indexers (0,1,2...) on the groups.

Groups are not the same as Captures. The 0'th group is the entire string.

See http://www.dotnetcoders.com/web/Learning/Regex/groups.aspx for some
examples.


Lee Chapman said:
I am thinking about using a regex to parse a string of data. My regex is of
the form

(?'m1'string1)|(?'m2'string2)|(?'m3'string3) etc.

I can get a match through Match.Captures[0], but I can't seem to find anyway
to get the 'mx' information from the Capture object. Is this possible? I
don't want to have to test each Match.Groups["mx"].Success for all possible
mx's... How can I get the capture name from the match?

Thanks,
- Lee
 
Back
Top