han*_*ant 18 java regex string
我有一个字符串,例如
String src = "How are things today /* this is comment *\*/ and is your code /*\* this is another comment */ working?"
Run Code Online (Sandbox Code Playgroud)
我想从字符串中删除/* this is comment *\*/ 和/** this is another comment */子src串.
我尝试使用正则表达式但由于经验不足而失败.
Wik*_*żew 30
在最好的多行注释的正则表达式是一个展开的版本(?s)/\*.*?\*/,看起来像
String pat = "/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";
Run Code Online (Sandbox Code Playgroud)
请参阅regex101.com上的正则表达式解释.
简而言之,
/\*- 匹配评论开始,/*以及之后的任何0+星号[^*]*\*+- 匹配0+字符,而不是*1+字面*(?:[^/*][^*]*\*+)* - 0+序列:
[^/*][^*]*\*+- 不是a /或*(匹配[^/*])后跟0+非星号字符([^*]*)后跟1+星号(\*+)/ - 结束 /David的正则表达式需要26步才能在我的示例字符串中找到匹配项,而我的正则表达式只需要12步.有了巨大的输入,David的正则表达式可能会因堆栈溢出问题或类似问题而失败,因为.*?由于正则表达式引擎执行的每个位置的延迟模式扩展,懒惰点匹配效率低,而我的模式一次性匹配线性文本块.
Dav*_*amp 15
尝试使用此正则表达式(仅限单行注释):
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);
Run Code Online (Sandbox Code Playgroud)
REGEX解释说:
从字面上匹配字符"/"
字面上匹配字符"*"
"" 匹配任何单个字符
"*?" 在零和无限次之间,尽可能少的时间,根据需要扩展(懒惰)
字面上匹配字符"*"
从字面上匹配字符"/"
或者,通过添加(?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);
Run Code Online (Sandbox Code Playgroud)
参考: