Use the Regex.Replace method to specify a replacement string that will allow you to format the captured groups. An example is:
string input = "[check out this URL!](http://www.reallycoolURL.com)"; string pattern = @"\[(?<Text>[^]]+)]\((?<Url>[^)]+)\)"; string replacement = @"<a href=""${Url}"">${Text}</a>"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result);
Note that I use named capture groups in the template, which allows me to refer to them as ${Name} in the replacement string. You can easily structure a replacement in this format.
Breakdown of the structure:
\[(?<Text>[^]]+)] : match the open square bracket and capture everything that is not the closing square bracket into the named group of captured texts. Then match the closing square bracket. Note that the closing square bracket must not be escaped within a character class group. However, it is important to avoid an open square bracket.\((?<Url>[^)]+)\) : the same idea, but with parentheses and capturing to the named Url group.
Named groups help with clarity, and regex patterns can benefit from all the clarity they can get. For completeness, the same approach is used here without using the named groups, in which case they are numbered:
string input = "[check out this URL!](http://www.reallycoolURL.com)"; string pattern = @"\[([^]]+)]\(([^)]+)\)"; string replacement = @"<a href=""$2"">$1</a>"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result);
In this case, ([^]]+) is the first group, denoted by $1 in the replacement pattern, and the second group ([^)]+) , referred to by $2 .
Ahmad mageed
source share