Java - 正则表达式 - 删除评论 [英] Java - Regex - Remove comments

查看:114
本文介绍了Java - 正则表达式 - 删除评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除Java代码中的注释。我看过很多例子,但每个都写错了。



以下是代码示例:

  String somestring =http://google.com; ////google.com;将被删除

另一个例子:

  get.setHeader(Accept,* / *); /// *);以后将被删除

但我想要正确的正则表达式来处理这些情况



我试过:



如果我们然后用第一个捕获组替换每个匹配,那么每个匹配都没有捕获组(即a评论)已删除:



Regex101替代演示



我所采用的更为通用的匹配条件a | b | c -technique的说明此处


I want to remove comments in Java code. I have seen a lot of examples, but each was written wrong.

Here is example of code:

String somestring = "http://google.com"; // "//google.com";" is going to be removed

Another example:

    get.setHeader("Accept", "*/*"); // "/*");" and later is going to be removed too

But I want right regular expression which handles those cases

I tried: http://ostermiller.org/findcomment.html Regular expression to remove comment and other popular examples

It should handle common cases:

somemethod();//it should be removed
somemethod(); /* some comment that may end on other line */

But should be handled and other situations:

String somestring = "http://google.com"; // url shouldn't be touched
get.setHeader("Accept", "*/*"); // "*/*" shouldn't be touched too

解决方案

Already commented this but lets see how far we get. Java doesn't do regex literals so stripping that one from this answer we get the following regex:

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

Debuggex Demo

If we then "replace" every match with the first capture group, every match that doesn't have a capture group to begin with (i.e. a comment) is removed:

Regex101 substitution Demo

A explanation of the more generic "match this except in conditions a|b|c"-technique I employed is available here.

这篇关于Java - 正则表达式 - 删除评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆