我可以使用此正则表达式(带有RegexOptions.Singleline)完全匹配块注释(/* comment */):
(\/\*[\w\W]*\*\/)
我也可以使用此正则表达式(带有RegexOptions.Multiline)完全匹配行注释(// comment):
(//((?!\*/).)*)(?!\*/)[^\r\n]
[^\r\n]
而不是$
,因为$
也包括匹配中的\r
。但是,这并不完全符合我的要求。
这是我要匹配的测试代码:
// remove whole line comments
bool broken = false; // remove partial line comments
if (broken == true)
{
return "BROKEN";
}
/* remove block comments
else
{
return "FIXED";
} // do not remove nested comments */ bool working = !broken;
return "NO COMMENT";
这个短语的意思是“块表达式匹配”。
/* remove block comments
else
{
return "FIXED";
} // do not remove nested comments */
这很好,但是行表达式匹配。
// remove whole line comments
// remove partial line comments
and
// do not remove nested comments
另外,如果我在行表达式中没有两次使用“*/”正向预查,则匹配。
// do not remove nested comments *
我真的不想要那个。
我想要的是一个表达式,它将匹配从//
开始到行末的字符,但在//
和行末之间不包含*/
。
另外,只是为了满足我的好奇心,有人能解释一下为什么我需要两次前瞻吗?(//((?!\*/).)*)[^\r\n]
和(//(.)*)(?!\*/)[^\r\n]
都会包括星号,但(//((?!\*/).)*)(?!\*/)[^\r\n]
和(//((?!\*/).)*(?!\*/))[^\r\n]
不会。
string foo = "http://stackoverflow.com;"
? - Anthony Pegram/* ... */
模式由于贪婪性而过度匹配,例如考虑/* comment1 */ not-a-comment! /* comment2 */
。 - polygenelubricants