排除注释的正则表达式?

A regular expression to exclude a Comments?

我有一个正则表达式如下:

(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)

而我的测试字符串如下:

<?
/* This is a comment */

cout << "Hello World"; // prints Hello World

/*
 * C++ comments can  also
 */

cout << "Hello World"; 

/* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/

echo "//This line was not a Comment, but ... ";
echo "http://whosebug.com";
echo 'http://whosebug.com/you can not match this line';
array = ['//', 'no, you can not match this line!!']
/* This is * //a comment */

https://regex101.com/r/lx2f5F/1

能正确匹配第2、4、7~9、13~17行

但它也匹配最后一行的单引号(')、双引号(")和数组, 如何进行非贪婪匹配?

如有任何帮助,我们将不胜感激。

有了PCRE你可以使用(*SKIP)(*FAIL)机制:

([\'\"])(?<!\).*?(*SKIP)(*FAIL)
|
(?|
    (?P<comment>(?s)/\*.*?\*/(?-s))
    |
    (?P<comment>//.+)
)

a working demo on regex101.com
注意:分支重置 (?|...) 在这里并不是真正需要的,只是用来清除名为 comment 的组。

我相信我有一个新的最佳模式给你。
/\/\*[\s\S]*?\*\/|(['"])[\s\S]+?(*SKIP)(*FAIL)|\/{2}.*/
这将在 683 步内准确处理以下文本块:

<?
/* This is a comment */

cout << "Hello World"; // prints Hello World

/*
 * C++ comments can  also
 */

cout << "Hello World"; 

/* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/

echo "//This line was not a Comment, but ... ";
echo "http://whosebug.com";
echo 'http://whosebug.com/you can not match this line';
array = ['//', 'no, you can not match this line!!']
/* This is * //a comment */

模式说明:(Demo *您可以使用底部的替换框将评论子字符串替换为空字符串——有效地删除所有评论。)

/\/\*[\s\S]*?\*\/ 匹配 \* 然后 0 个或更多字符然后 */
|
(['"])[\s\S]*?(*SKIP)(*FAIL) 不匹配 '" 然后是 1 个或多个字符然后是前导(捕获)字符
|
\/{2}.*/ 匹配 // 然后零个或多个非换行符

使用 [\s\S] 类似于 . 除了它允许换行符,这是在前两个选项中特意使用的。第三种选择有意使用 . 在发现换行符时停止。

我已经检查了每一个备选方案序列,以确保最快的备选方案排在第一位并且优化了模式。我的模式与 OP 的示例输入正确匹配。如果有人发现我的模式有问题,请给我留言,以便我可以尝试修复它。


Jan 的模式在 1006 步 中正确匹配了 OP 所需的所有子字符串,使用:~([\'\"])(?<!\).*?(*SKIP)(*FAIL)|(?|(?P<comment>(?s)\/\*.*?\*\/(?-s))|(?P<comment>\/\/.+))~gx

Sahil 的模式无法 完全匹配您 UPDATED 示例输入中的最终评论。这意味着问题要么是错误的,应该作为 "unclear what you are asking" 关闭,要么 Sahil 的答案是错误的,它不应该被授予绿色勾号。当您更新问题时,您应该要求 Sahil 更新他的答案。当错误的答案无法满足问题时,未来的 SO 读者可能会感到困惑,并且 SO 成为不太可靠的资源。