Reputation: 1595
I need the match in the Regex.Replace to be part of the replacement string. For example, if I want to change DOMAIN to <a>DOMAIN</a>
, wherever it says DOMAIN. How do I get DOMAIN into the match?
regex.Replace(input, String.Format("<a>{0}</a>" WHAT_HERE?));
How do I find the "WHAT_HERE?"?
Upvotes: 0
Views: 69
Reputation: 24395
Andrew's answer is correct, here's how you'd do it if you wanted to name the grouping and then replace it by name (expanded from Andrew's dotnetfiddle):
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string result = Regex.Replace("This is a test to see if DOMAIN gets replaced properly. DOMAIN", "(?<myName>DOMAIN)", "<a>${myName}</a>");
result.Dump();
}
}
Output:
This is a test to see if <a>DOMAIN</a> gets replaced properly. <a>DOMAIN</a>
Upvotes: 0
Reputation: 126052
You can use a grouping construct (...)
:
string replaced = Regex.Replace("<input>", "(DOMAIN)", "<a>$1</a>");
Example: https://dotnetfiddle.net/Hu0cEO
Upvotes: 1