Java - 正则表达式 - 删除评论

时间:2015-02-09 13:35:58

标签: java regex

我想删除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 Regular expression to remove comment 和其他流行的例子

它应该处理常见的情况:

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

1 个答案:

答案 0 :(得分:5)

已经对此进行了评论,但让我们看看我们能走多远。 Java不执行正则表达式文字,因此从this answer中剥离出一个正则表达式:

((['"])(?:(?!\2|\\).|\\.)*\2)|\/\/[^\n]*|\/\*(?:[^*]|\*(?!\/))*\*\/

Regular expression visualization

Debuggex Demo

如果我们然后“替换”每个匹配第一个捕获组,则删除每个没有捕获组的匹配(即注释):

Regex101 substitution Demo

对于更通用的“匹配此情况的解释除了条件a | b | c” - 我使用的技术可用here