[英]Why does Regex.Replace leave parenthesis?
Lets say you have: 假设您有:
string result = Regex.Replace("people (MANY)", "(many)", "", RegexOptions.IgnoreCase);
Then after this result will be people ()
. 然后在此结果之后将是people ()
。 Why is this and how do I alter the regex replace to remove the brackets too? 为什么会这样,以及如何更改正则表达式替换来也删除括号?
In regex there is a set of characters that can have a special meaning (\\, *, +, ?, |, {, [, (,), ^, $,., #, and white space), if you want them always represented in your pattern you need to escape them. 如果需要,在正则表达式中有一组可以具有特殊含义的字符(\\,*,+,?,|,{,[,(,),^,$,。,#和空白))始终以您的模式表示,则需要对其进行转义。
There is a general function Regex.Escape
that will go through the above list and escape every instance it finds for you. 有一个常规函数Regex.Escape
会通过上面的列表,并转义它为您找到的每个实例。
Regex.Escape("(many)") // this becomes \(many\)
You have to escape them: http://msdn.microsoft.com/en-us/library/4edbef7e(v=vs.110).aspx 您必须逃脱它们: http : //msdn.microsoft.com/zh-cn/library/4edbef7e(v=vs.110).aspx
The following characters have to be escaped in Regular Expressions because they have a meaning in pattern matching: 以下字符必须在正则表达式中转义,因为它们在模式匹配中具有含义:
. 。 $ ^ { [ ( | ) * + ? $ ^ {[(|)* +? \\ \\
You can escape this special chars with the backslash \\
in your case \\(
and \\)
你可以逃避用反斜杠这个特殊字符\\
你的情况\\(
和\\)
Your code changed accordingly: 您的代码进行了相应的更改:
string result = Regex.Replace("people (MANY)", "\(many\)", "", RegexOptions.IgnoreCase);
That is because the parenthesis have a meaning in Regex patterns. 这是因为括号在Regex模式中具有含义。 They define a capturing group . 他们定义了一个捕获小组 。
Escape the parenthesis, so that they are not seen as special characters but as parenthesis: 转义括号,以使它们不被视为特殊字符,而是括号:
string result = Regex.Replace("people (MANY)", @"\(many\)", "", RegexOptions.IgnoreCase);
change it to 更改为
string result = Regex.Replace("people (MANY)", @"\(many\)", "", RegexOptions.IgnoreCase);
The () mean something special to the regex engine, so you have to escape them. ()对正则表达式引擎来说是特殊的东西,因此您必须对其进行转义。
方括号是用于分组的特殊字符,您需要对其进行转义:
Regex.Replace("people (MANY)", @"\(many\)", "", RegexOptions.IgnoreCase);
Parenthesis in a regex let you define a capture group . 正则表达式中的括号使您可以定义捕获组 。 You need to escape them for them to be considered as regular characters 您需要对其进行转义才能将其视为常规字符
Parentheses have a special meaning in regexes -- they're for capturing (so in the replace you could use $1 and it would give you what was in the parens). 括号在正则表达式中有特殊含义-用于捕获 (因此在替换中,您可以使用$ 1,这会给您括号中的内容)。 If you want a literal you have to escape them: \\( 如果要使用文字,则必须转义它们:\\(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.