c# - 转义右括号

标签 c# regex

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/

相关文章:

c# - 如何访问添加到 HashSet 的最后一个对象?

C#如何使用字符串插值设置固定字段宽度?

C# DirectInput - 确定游戏 handle Controller 类型

c# - 相当于 RNGCryptoServiceProvider 的 JavaScript

java - 是否可以使用 $x 从 Matcher 获取组?

c# - 如果缺少数字,Linq 拆分组

c++ - 使用正则表达式 C++ 计算数字中的小数位

javascript - 正则表达式在javascript中跨越-9.99到0的范围

javascript - 正则表达式从字符串中捕获域名,包括特定顶级域名的电子邮件地址

javascript - 如何查看 url 是否仅限移动设备