System.Text.RegularExpressions.Regex.Escape()
仅转义左大括号。是否有一种 .NET Framework 方法可以转义正则表达式中使用的右大括号?我似乎找不到任何东西。我不想对字符进行硬编码。
编辑:我需要为平衡组定义生成“(?<-open>)”标签。我收到一个代表结束定界符的字符列表,对它们进行转义,然后将它们添加到“(?<-open>)”标记中的表达式中。所以,是的,我确实也必须避开右大括号。
最佳答案
如上面评论所述,Escape 函数的行为如下 ( MSDN ):
Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.
添加以下备注:
While the Escape method escapes the straight opening bracket ([) and opening brace ({) characters, it does not escape their corresponding closing characters (] and }). In most cases, escaping these is not necessary. If a closing bracket or brace is not preceded by its corresponding opening character, the regular expression engine interprets it literally. If an opening braket or brace is interpreted as a metacharacter, the regular expression engine interprets the first corresponding closing character as a metacharacter. If this is not the desired behavior, the closing bracket or brace should be escaped by explicitly prepending the backslash () character. For an illustration, see the Example section.
因此,如果解释器发现 }
前面没有开头的 {
,它将自动转义它。
关于c# - 转义右括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8240997/