I am having a regex to identify some named groups. There are a few cases which have multiple groups with different patterns. The problem is to have all named groups into corresponding lists. The constraint is that I cannot have more than one regex and I cannot call execute the regex more than once. I have tried following code, but it always returns second pattern:
Regex reg = new Regex(@"(?<n1>pattern_n1_1) (?<n2>pattern_n2_1) (?<n1>pattern_n1_2) (?<n2>pattern_n1_2)", RegexOptions.IgnoreCase);
String str = "pattern_n1_1 pattern_n2_1 pattern_n1_2 pattern_n1_2";
List<String> matchedText = new List<string>();
List<String> string_n1 = new List<string>();
List<String> string_n2 = new List<string>();
MatchCollection mc = reg.Matches(str);
if (mc != null)
{
foreach (Match m in mc)
{
matchedText.Add(m.Value.Trim());
string_n1.Add(m.Groups["n1"].Value);
string_n2.Add(m.Groups["n2"].Value);
}
}
Here the list string_n1 and string_n2 has one element each. string_n1 has "pattern_n1_2" and string_n2 has "pattern_n2_2". However, I require both "pattern_n1_1" and "pattern_n1_2" to be in string_n1 AND both "pattern_n2_1" and "pattern_n2_2" to be in string_n2
pattern_n2_2, notpattern_n1_2. The error is repeated in the corresponding portion of the regex.