Replace only some groups with Regex
Let's suppose I have the following regex:
-(\d+)-
and I want to replace, using C#, the Group 1 (\d+)
with AA
, to obtain:
-AA-
Now I'm replacing it using:
var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.Replace(text, pattern, "-AA-");
But I don't really like this, because if I change the pattern to match _(\d+)_
instead, I will have to change the replacement string by _AA_
too, and this is against the DRY principle.
I'm looking for something like:
Keep the matched text exactly how it is, but change Group 1 by this text
and Group 2 by another text
...
Edit:
That was just an example. I'm just looking for a generic way of doing what I said above.
It should work for:
anything(\d+)more_text
and any pattern you can imagine.
All I want to do is replace only groups, and keep the rest of the match.
A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:
var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3");
or using a MatchEvaluator:
var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);
Another way, slightly messy, could be using a lookbehind/lookahead:
(?<=-)(\d+)(?=-)
You can do this using lookahead and lookbehind:
var pattern = @"(?<=-)\d+(?=-)";
var replaced = Regex.Replace(text, pattern, "AA");
I also had need for this and I created the following extension method for it:
public static class RegexExtensions
{
public static string ReplaceGroup(
this Regex regex, string input, string groupName, string replacement)
{
return regex.Replace(
input,
m =>
{
var group = m.Groups[groupName];
var sb = new StringBuilder();
var previousCaptureEnd = 0;
foreach (var capture in group.Captures.Cast<Capture>())
{
var currentCaptureEnd =
capture.Index + capture.Length - m.Index;
var currentCaptureLength =
capture.Index - m.Index - previousCaptureEnd;
sb.Append(
m.Value.Substring(
previousCaptureEnd, currentCaptureLength));
sb.Append(replacement);
previousCaptureEnd = currentCaptureEnd;
}
sb.Append(m.Value.Substring(previousCaptureEnd));
return sb.ToString();
});
}
}
Usage:
var input = @"[assembly: AssemblyFileVersion(""2.0.3.0"")][assembly: AssemblyFileVersion(""2.0.3.0"")]";
var regex = new Regex(@"AssemblyFileVersion\(""(?<version>(\d+\.?){4})""\)");
var result = regex.ReplaceGroup(input , "version", "1.2.3");
Result:
[assembly: AssemblyFileVersion("1.2.3")][assembly: AssemblyFileVersion("1.2.3")]