尝试使用此正则表达式(仅限单行注释):
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);
正则表达式解释说:
按字面意思匹配字符“/”
按字面意思匹配字符“*”
"."匹配任何单个字符
"*?"在零次和无限次之间,尽可能少地扩展,根据需要扩展(懒惰)
按字面意思匹配字符“*”
按字面意思匹配字符“/”
或者,这里是正则表达式,用于单行和多行注释,方法是添加 (?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);
参考: