Java正则表达式以匹配C样式的多行注释

我有一个字符串例如

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 */src字符串。

我尝试使用正则表达式,但由于经验不足而失败。

回答:

尝试使用此正则表达式(仅单行注释):

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解释:

从字面上匹配字符“ /”

从字面上匹配字符“ *”

“。” 匹配任何单个字符

“ *?” 在0到无限制的时间之间,尽可能少的时间,根据需要扩展(延迟)

从字面上匹配字符“ *”

从字面上匹配字符“ /”

另外,这里是通过添加(?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);

以上是 Java正则表达式以匹配C样式的多行注释 的全部内容, 来源链接: utcz.com/qa/416821.html

回到顶部