Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - Handling regex escape replacement text that contains the dollar character

string input = "Hello World!";
string pattern = "(World|Universe)";
string replacement = "$1";

string result = Regex.Replace(input, pattern, replacement);

Having the following example, the result would be "Hello World!", as the $1 gets replaced with the first group (World|Universe), however the result I want is "Hello $1!"

The Regex.Escape method is meant to be used to escape a Regex pattern, not the replacement, as it can escape other characters like slashes and other Regex pattern characters. The obvious fix to my problem is to have my replacement equal to "$$1", and will achieve "Hello $1!", but I was wondering if the dollar sign is the only value I have to escape (assuming replacement is user generated, and I do not know it ahead of time), or is there a helper function that does this already.

Does anyone know of a function to escape the replacement value that Regex.Replace(string input, string pattern, string replacement) uses?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From MSDN:

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions.

The following substitutions are defined:

  • $number
  • ${name}
  • $$
  • $&
  • $`
  • $'
  • $+
  • $_

Substitutions are the only special constructs recognized in a replacement pattern. None of the other regular expression language elements, including character escapes and the period (.), which matches any character, are supported. Similarly, substitution language elements are recognized only in replacement patterns and are never valid in regular expression patterns.

So it look like it's only the $ character that needs to be escaped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...