用于匹配 C 样式多行注释的正则表达式

2022-09-01 21:37:47

我有一个字符串,例如

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

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


答案 1

最好的多行注释正则表达式是一个展开的版本,看起来像(?s)/\*.*?\*/

String pat = "/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";

请参阅 regex101.com 中的正则表达式演示和说明

总之

  • /\*- 匹配评论开始/*
  • [^*]*\*+- 匹配 0+ 个字符,而不是后跟 1 个以上的文字**
  • (?:[^/*][^*]*\*+)*- 0+ 序列:
    • [^/*][^*]*\*+- 不是 a 或 (与 ) 后跟 0+ 非星号字符 () 后跟 1+ 星号 (/*[^/*][^*]*\*+)
  • /- 关闭/

David的正则表达式需要26个步骤才能在我的示例字符串中找到匹配项,而我的正则表达式只需要12个步骤。对于巨大的输入,David的正则表达式可能会因堆栈溢出问题或类似问题而失败,因为惰性点匹配效率低下,因为正则表达式引擎执行的每个位置的惰性模式扩展,而我的模式一次性匹配线性文本块。.*?


答案 2

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

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);

参考: