C# – Regex search and replace where the replacement is a mod of the search term


i'm having a hard time finding a solution to this and am pretty sure that regex supports it. i just can't recall the name of the concept in the world of regex.

i need to search and replace a string for a specific pattern but the patterns can be different and the replacement needs to "remember" what it's replacing.

For example, say i have an arbitrary string: 134kshflskj9809hkj

and i want to surround the numbers with parentheses,
so the result would be: (134)kshflskj(9809)hkj

Finding numbers is simple enough, but how to surround them?

Can anyone provide a sample or point me in the right direction?

Best Solution

In some various langauges:

// C#:
string result = Regex.Replace(input, @"(\d+)", "($1)");
// JavaScript:
thestring.replace(/(\d+)/g, '($1)');
// Perl:
// PHP:
$result = preg_replace("/(\d+)/", '($1)', $input);

The parentheses around (\d+) make it a "group" specifically the first (and only in this case) group which can be backreferenced in the replacement string. The g flag is required in some implementations to make it match multiple times in a single string). The replacement string is fairly similar although some languages will use \1 instead of $1 and some will allow both.