Count Submatches in a Regex


  • I want to know how you can count the number of submatches in a regular expression. I can't find a guranteed way of doing this normally in VB Script the number of submatches would be kept in:
    and the regex values would be kept in:

    but how would you do the same thing in the .NET Regex class? I found 2 things that might be it but none of them worked well for me: "Groups" and "Captures" I don't know which one holds submatches though. By submatch I am reffering to a string kept between brackets
    For example if my regex was "Name: (\w) - Age: (\d)" then I would have 2 submatches one would be my name matched by \w and the other one would be my age matched by \d.

    Any idea how I can do this?
    Thanks in advance
    (Moderator: Thread moved to the Regular Expression Forum and Title tweaked for quicker thread understanding during a search)
    Saturday, May 06, 2006 10:53 PM


  • The Submatches you are looking for are considered captures in the regex lingo. Each of the submatches can be found in the groups after group zero. Group Zero is always the match. For example changing up your regex to work, I match the whole item, but capture the subitems or submatches as you see them:

    Input TextName: Fred - Age: 25

    Regular Expression(?:Name:\s+)(\w*)(?:[^:]*:\s)(\d\d)

    Group CapturesGroups: (0) (1) (2)

    Match (1):
                  0 : Name: Fred - Age: 25
                  1 : Fred
                  2 : 25

    Thursday, March 01, 2007 10:23 PM