I want to escape the substitution part in a regex replace command in .NET:
public static string GetPriceMessage(string data, string price)
{
var repl = "This is a $1 priced at " + price + " suitable for $2.";
return Regex.Replace(data, "item_name: ([^;]+); suitable: ([^;]+)", repl);
}
var price = "$15/item";
var data = "item_name: Puzzle; suitable: all ages";
GetPriceMessage(data, price)
I want to make sure price
is substituted verbatim. Regex.Escape
doesn't work.
You only need to escape $
in substitutions, since all substitutions start with $
. Ie just use:
price.Replace("$", "$$");
See the following question for details: Handling regex escape replacement text that contains the dollar character
Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.
[...]
In a replacement pattern, $ indicates the beginning of a substitution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.