Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何仅在转义时捕获括号?_C#_Regex - Fatal编程技术网

C# 如何仅在转义时捕获括号?

C# 如何仅在转义时捕获括号?,c#,regex,C#,Regex,我对正则表达式的定义如下: regex = new Regex(@"^\(([^()]+)\)", RegexOptions.Multiline); 这对于处理以下内容非常有用: abc 123 (xyz) some things (more of the other) abc 123 (xyz) some things (111 \(look at this\) 999) (more of the other) 并返回组1匹配项: xyz more of the other 但是,当它

我对正则表达式的定义如下:

regex = new Regex(@"^\(([^()]+)\)", RegexOptions.Multiline);
这对于处理以下内容非常有用:

abc
123
(xyz)
some things
(more of the other)
abc
123
(xyz)
some things
(111 \(look at this\) 999)
(more of the other)
并返回组1匹配项:

xyz
more of the other
但是,当它遇到这样的文本时:

abc
123
(xyz)
some things
(more of the other)
abc
123
(xyz)
some things
(111 \(look at this\) 999)
(more of the other)
我想让它匹配

xyz
111 \(look at this\) 999
more of the other
但我不知道如何修改字符类
[^()]
,以指示在使用前面的“\”进行转义时可以接受括号。我试过:

^\((([^()]|\\\(|\\\))+)\)
但第一组的匹配项是:

xyz
111 \(look at this\
more of the other
注意第二个匹配中缺少的右括号

编辑:我忘了提到括号组后面可以有文本,不应该捕获,例如:

(more of the other) TB ff
应该只捕获

more of the other

您需要从字符类中排除反斜杠,否则第二个和第三个分支将与第一个转义字符不匹配。要允许对其他字符进行转义,您需要将括号替换为点:

\(((?>(?:[^()\\]|\\.)+))\)
您也可以这样写(更高效):


为什么不保持简单呢

^\((.+)\)$
如果
定义了行的开头和结尾,则这将匹配它们之间的所有内容。
例如:

别忘了设置多行模式


输入:

(111 \(look at this\) 999)
(more of the other)
abc
123
(xyz)
some things
结果:

Match 1
Full match  0-26    `(111 \(look at this\) 999)`
Group 1.    1-25    `111 \(look at this\) 999`
Match 2
Full match  27-46   `(more of the other)`
Group 1.    28-45   `more of the other`
Match 3
Full match  55-60   `(xyz)`
Group 1.    56-59   `xyz`

显示您的代码,特别是用于模式的字符串。是否有任何
\
\(
)在
(…)
)之外?因此,您希望匹配
之间的所有文本,而这些文本前面没有反斜杠?为什么不只是
^(.*)$
?如果括号定义了行的开始和结束,则将匹配括号中的所有内容。@Damien\u不信者,我想匹配未转义
之间的所有文本,包括转义括号
\(
\)
。这种方法不适用于字符串,例如。右括号后面可能有文本,例如
(其他更多)TB ff