Reputation: 695
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);
}
Upvotes: 2
Views: 1168
Reputation: 700172
You don't need to do any logic at all, that replacement can be done using group references in the replacement string:
string output = Regex.Replace(input, @"word(\d)-(\d)", "wd$1-$2");
Upvotes: 4
Reputation: 50104
You can pass Replace
a MatchEvaluator
. It's a delegate that takes a Match
and returns the string you want to replace it with.
e.g.
string output = re.Replace(
input,
m => "wd" + m.Groups[1].Value + "-" + m.Groups[2].Value);
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 like word(?=\d-\d)
and then just replace it with wd
.
Upvotes: 2