我有一个字符串用于例如正则表达式匹配C风格的多行注释
String src = "How are things today /* this is comment *\*/ and is your code /*\* this is another comment */ working?"
我想从src
字符串中删除/* this is comment *\*/
和/** this is another comment */
子。
我试图使用正则表达式,但由于较少的经验失败。
我有一个字符串用于例如正则表达式匹配C风格的多行注释
String src = "How are things today /* this is comment *\*/ and is your code /*\* this is another comment */ working?"
我想从src
字符串中删除/* this is comment *\*/
和/** this is another comment */
子。
我试图使用正则表达式,但由于较少的经验失败。
尝试使用这个正则表达式(仅单行注释):
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);
正则表达式的解释:
匹配字符 “/” 的字面
匹配字符 “*”字面意思是
“。”匹配任何单个字符
“*?”之间的零和无限的时间,尽可能少的时间,尽可能需要(懒惰)
匹配字符“*”的字面
匹配的字符扩大 “/”的字面
或者这里通过添加的正则表达式单和多行注释(一个或多个):
//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);
参考:
当你有一个包含注释序列的字符串时,它会很有趣。 – nhahtdh
你能解释多线正则表达式的工作原理吗?我不明白*(?s)*(并且链接在这方面没有帮助)。 – brimborium
@nhahtdh +1 Lol是完全的另一个故事(我猜你只是检查字符串之前的任何冲突的一系列字符,并替换它们的东西安全,直到正则表达式完成,然后将它们替换回来? –
System.out.println(src.replaceAll("\\/\\*.*?\\*\\/ ?", ""));
您必须使用非贪心量词?得到正则表达式的工作。 我还加了'?'在正则表达式的结尾删除一个空间。
的最好多行注释的正则表达式是(?s)/\*.*?\*/
已展开的版本,看起来像
String pat = "/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/";
见/\*[^*]*\*+(?:[^/*][^*]*\*+)*/
regex demo和regex101.com的解释。
总之,
/\*
- 匹配的注释开始/*
[^*]*\*+
- 比*
随后与1+字面*
(?:[^/*][^*]*\*+)*
其他匹配0+字符 - 0+序列:
[^/*][^*]*\*+
- 不是/
或*
(与[^/*]
匹配),随后用0+非星号字符([^*]*
),接着用星号1+(\*+
)/
- 闭/
David's regex需要26个步骤找到匹配我的示例字符串,并且my regex只需要12步。由于输入数据量巨大,David的正则表达式很可能会因为堆栈溢出问题或类似的问题而失败,因为由于在正则表达式引擎执行的每个位置上的懒惰模式扩展,懒惰点匹配效率低下,而我的模式一次匹配线性块文本。
你是怎么想出来的? –
@ AT-Aoi它基本上取自*掌握正则表达式*,*删除C注释*部分。 –
试试这个它为我工作:
System.out.println(src.replaceAll("(\/\*.*?\*\/)+",""));
用正则表达式解析Java代码是不是我推荐。 – Confluence
@Confluence,我不确定什么可能是实现结果的最佳选择?你能建议一个吗? – hanumant
你试过什么正则表达式?正如你已经说过你已经尝试了一些东西,你可以把它粘贴在这里,以便我们看到你的方法。根据您的经验,我们可以更多/更少地了解解决方案。 – brimborium