Java – 正则表达式 – 删除评论
我想删除Java代码中的注释。 我看过很多例子,但每个都写错了。
这是代码示例:
String somestring = "http://google.com"; // "//google.com";" is going to be removed
另一个例子:
get.setHeader("Accept", "*/*"); // "/*");" and later is going to be removed too
但我想要正确的正则表达式来处理这些情况
我试过: http : //ostermiller.org/findcomment.html 正则表达式删除评论和其他流行的例子
它应该处理常见的情况:
somemethod();//it should be removed somemethod(); /* some comment that may end on other line */
但应该处理和其他情况:
String somestring = "http://google.com"; // url shouldn't be touched get.setHeader("Accept", "*/*"); // "*/*" shouldn't be touched too
已经评论了这一点,但让我们看看我们得到了多远。 Java没有使用正则表达式文字,所以从这个答案中删除一个我们得到以下正则表达式:
((['"])(?:(?!\2|\\).|\\.)*\2)|\/\/[^\n]*|\/\*(?:[^*]|\*(?!\/))*\*\/
Debuggex演示
如果我们然后用第一个捕获组“替换”每个匹配,则删除每个没有捕获组的匹配(即注释):
Regex101替换演示
在 这里可以获得更通用的“匹配除了条件a | b | c之外的技术”这一技术的解释。