I have the following code, (note I am talking about c#/.net here since some of this is subtly different in other variants of regex):
var str = @"abc(?<cg1>.*)def(?<cg2>((?<cg3>[0-9])-)+)";
var regex = new Regex(str);
var test = "abcxyzdef1-2-3-";
var match = regex.Match(test);
This matches strings like this:
abc xyz def 1-2-3-
abc
.* This is called cg1
def
([0-9]-)+ This is called cg2
However, I also have an embedded group in cg2 where each digit is its own group – cg3.
So test running this the groups I got are:
match[0]: abcxyzdef1-2-3-
match[1]. 3-
match[2]. cg1 xyz
match[3]. cg2 1-2-3-
match[4]. cg3 3
It seems that cg3 only captures the last instance of that group, namely the last 3.
Is there a way using groups to get all instances where cg3 matched, or would I have to get cg2 and rerun the match just on that? Viz:
var cg2 = match.Groups["cg2"];
var innerRegex = new Regex("(?<digit>[0-9])-");
var innerMatches = innerRegex.Matches(cg2.Value);
foreach (Match m in innerMatches)
{
Debug.WriteLine(m.Groups["digit"].Value);
}