I’ve looked high and low for an example of how to implement a Regex global replace in C# where there are Groups involved, but I’ve come up empty. So I wrote my own. Can anyone suggest a better way to do this?
static void Main(string[] args)
{
Regex re = new Regex(@"word(\d)-(\d)");
string input = "start word1-2 filler word3-4 end";
StringBuilder output = new StringBuilder();
int beg = 0;
Match match = re.Match(input);
while (match.Success)
{
// get string before match
output.Append(input.Substring(beg, match.Index - beg));
// replace "wordX-Y" with "wdX-Y"
string repl = "wd" + match.Groups[1].Value + "-" + match.Groups[2].Value;
// get replacement string
output.Append(re.Replace(input.Substring(match.Index, match.Length), repl));
// get string after match
Match nmatch = match.NextMatch();
int end = (nmatch.Success) ? nmatch.Index : input.Length;
output.Append(input.Substring(match.Index + match.Length, end - (match.Index + match.Length)));
beg = end;
match = nmatch;
}
if (beg == 0)
output.Append(input);
}
You can pass
ReplaceaMatchEvaluator. It’s a delegate that takes aMatchand returns the string you want to replace it with.e.g.
Alternatively, and I’m less sure about this, you could use lookahead – “check that this text follows, but don’t include it in the match”. The syntax is
(?=whatver)so I think you’d need something likeword(?=\d-\d)and then just replace it withwd.