正则expression式匹配一个C风格的多行注释
我有一个例如string
String src = "How are things today /* this is comment *\*/ and is your code /*\* this is another comment */ working?"
我想删除/* this is comment *\*/和/** this is another comment */ srcstring的子string。
我试图使用正则expression式,但由于较less的经验失败。
尝试使用这个正则expression式(仅限单行注释):
String src ="How are things today /* this is comment */ and is your code /* this is another comment */ working?"; String result=src.replaceAll("/\\*.*?\\*/","");//single line comments System.out.println(result);
REGEX解释说:
字面上匹配字符“/”
字面上匹配字符“*”
“” 匹配任何单个字符
“*?” 在零和无限次之间,尽可能less的次数,根据需要扩大(懒惰)
字面上匹配字符“*”
字面上匹配字符“/”
另外这里是单行和多行注释的正则expression式,join(?s) :
//note the added \n which wont work with previous regex String src ="How are things today /* this\n is comment */ and is your code /* this is another comment */ working?"; String result=src.replaceAll("(?s)/\\*.*?\\*/",""); System.out.println(result);
参考:
最好的多行注释正则expression式是(?s)/\*.*?\*/的展开版本
String pat = "/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";
请参阅regex101.com上的/\*[^*]*\*+(?:[^/*][^*]*\*+)*/ regex demo 。
简而言之,
-
/\*– 匹配注释开始/* -
[^*]*\*+– 匹配除*以外的0个以上的字符,并跟随1个字符* -
(?:[^/*][^*]*\*+)*– 0+序列:-
[^/*][^*]*\*+– 非0或非星号字符([^*]*),后跟1个星号(\*+)
-
-
/– closures/
大卫的正则expression式需要26个步骤来find我的示例string中的匹配, 我的正则expression式只需要12个步骤 。 有了巨大的投入,大卫的正则expression式可能会因堆栈溢出问题或类似的东西而失败,因为.*? 懒点匹配由于在正则expression式引擎执行的每个位置处的延迟模式扩展而效率低下,而我的模式一次匹配线性块文本。
System.out.println(src.replaceAll("\\/\\*.*?\\*\\/ ?", ""));
你必须使用非贪婪量词? 得到正则expression式的工作。 我还加了一个'?' 在正则expression式的结尾删除一个空格。