处理一个包含美元字符转义正则表达式替换文本 [英] Handling regex escape replacement text that contains the dollar character

查看:399
本文介绍了处理一个包含美元字符转义正则表达式替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



具有下面的例子,其结果必然是的Hello World!,因为 $ 1 获取与第一组所取代(世界|宇宙),但是结果,我要的是你好$ 1!

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!"

Regex.Escape 的方法,就是要用来逃跑的正则表达式,而不是替代,因为它可以逃脱其他人物,如斜线和其他正则表达式模式字符。最明显的修复我的问题是有我更换等于$$ 1,并实现你好$ 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.

有谁知道一个函数来逃避替换值 Regex.Replace(字符串输入,细绳纹,字符串替换)使用

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

推荐答案

从的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.

以下替换的定义


  • $号

  • $ {名}

  • $

  • $&​​安培;

  • $`

  • $

  • $ +

  • $ _

  • $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.

这篇关于处理一个包含美元字符转义正则表达式替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆