I'm validating a string that must consist of a prefix that matches a pattern (call it pat1
), followed by 0 or more repeating patterns, each containing 3 sub-patterns (pat2
, pat3
, pat4
) that I'd like to capture individually. Simplified a bit, the regex basically looks like this:
^pat1 ((pat2) (pat3) (pat4))*$
The ^
and $
anchors are present because the match should fail if the string contains any extraneous characters at the beginning or end.
Using Regex.Match
against a valid expression, I get a Match
object with the following characteristics:
- 5
Groups
, consisting of the entire expression, the last matched group (i.e. last occurrence ofpat2 pat3 pat4
), and matches for the lastpat2
,pat3
, andpat4
individually. That's all well documented and exactly as expected. Groups[1].Captures
containing aCapture
for each occurrence ofpat2 pat3 pat4
. Also as expected.
What I can't figure out how to do is extract pat2
, pat3
, and pat4
indidually from each Capture
. Is this even possible with a single execution of a single Regex? I'm starting to think not. (If Capture
had a Groups
property, that's probably exactly what I'd need. But it doesn't.)
If I take a completely different approach using Regex.Matches
instead of Regex.Match
, I think I could capture all the individual bits I need, but it wouldn't validate that the string cannot contain extraneous characters before, after, or between the matches.
So what I've resorted to for now is executing the original expression, iterating through Groups[1].Captures
and executing a Regex again (this time just (pat2) (pat3) (pat4)
) just to parse out the 3 groups within each capture. This feels like I'm making the engine repeat work that's already been done, but maybe it's the only way?
As a side-note, I did a lot of searching for "groups within captures", etc., and was very surprised to come up empty. I would think this is a common scenario, which makes me wonder if I should be taking a completely different approach. I'm open to any suggestion that meets all validation and capturing requirements in a reasonably efficient manner.