[2.0] [resolved] Regex String Replacement Question
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:
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>");
}
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.
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:
Code:
"<tag>ab</tag>9 <tag>a b</tag>123 <tag>ab</tag>4 <tag>ab</tag>2"
but the duplicate matches cause each "ab" to be replaced multiple times so the result is:
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?
Re: [2.0] Regex String Replacement Question
try this:
Code:
public void ReplaceProcess()
{
string str = "ab9 a b123 ab4 ab2";
string sR = "a[ \t]*b(?=[0-9]+)";
Regex r = new Regex(sR);
MatchEvaluator myEvaluator = new MatchEvaluator(ReplaceMe);
str = r.Replace(str, myEvaluator );
MessageBox.Show(str);
}
public string ReplaceMe(Match m)
{
return "<tag>" +m+"</tag>";
}