I have a string that I'm using a Regular Expression to look for matches. The problem I have is if there are duplicate matches returned in Regex.Matches(...) and I loop through each match to do a String.Replace to format the matches, they will be replaced duplicate times, at least as many times as there are duplicates found.
Example:
The code is looking for 'a' followed by zero or more spaces or tabs, followed by 'b' and looks behind, but doesn't include in the match, one or more numbers.Code:string str = "ab9 a b123 ab4 ab2"; foreach (Match m in Regex.Matches(str, "a[ \t]*b(?=[0-9]+)")) { //MessageBox.Show(m.Value); str = str.Replace(m.Value, "<tag>" + m.Value + "</tag>"); }
So the matches come back as "ab", "a b", "ab", and "ab" and I want to wrap each match with <tag></tag>
What I want is for the result string to look like:
but the duplicate matches cause each "ab" to be replaced multiple times so the result is:Code:"<tag>ab</tag>9 <tag>a b</tag>123 <tag>ab</tag>4 <tag>ab</tag>2"
Code:<tag><tag><tag>ab</tag></tag></tag>9 <tag>a b</tag>123 <tag><tag><tag>ab</tag></tag></tag>4 <tag><tag><tag>ab</tag></tag></tag>2
Is there any way around this other than storing the matches in a unique list and looping through the unique list instead of the Matches list?




Reply With Quote