用于匹配外括号但忽略带方括号的注释行的正则表达式



我正在尝试创建一个正则表达式来匹配外括号,但忽略了外括号内注释行中的括号。

示例字符串:

(
this is an example;
// this is a comment line with an '(' in it and should be ignored
this is (another) line;
)

我目前的正则表达式:

(((?>((?<c>)|[^()]+|)(?<-c>))*(?(c)(?!))))

这就是,我得到的:

(' in it and should be ignored
this is (another) line;
)

但我需要这个:

this is an example;
// this is a commentline with an '(' in it and should be ignored
this is (another) line;

以下是执行此操作的方法。

  • 使用(?<=()(.*?)(?=))使用look around断言的演示。

  • 使用((.*?))使用捕获组的演示。捕获1 .

注: 使用DOTOALL标志s允许.匹配的换行符。

使用量词?修复了lazy演示。


上述正则表达式在许多情况下都有效。在OP的许多其他规范之后,这里是最终的演示。

最终演示

试试这个

((([^)]+)|(//[^n]+n)))

最新更新