开发者

regular expression to match java class/interface/enum/annotation definition

I created a regular expression bellow to do this. Bu开发者_如何学JAVAt it also matches comments like //This class blabla...

\\S*.*\\s*(class|interface|enum|@interface)\\s+.*

Would you help me come out a regular expression to match the java class/interface/etc.. definition only?

Thanks.


Just change \S*.\s to ^\s* should do the trick. Then you will only match beginning of the line, any number of whitespace and then the keyword. Of course that would not match a line like "/* comment */ class MyClass", but that would be a pretty unusual one anyway.

^\s*(class|interface|enum|@interface)\s+.*


Regex is not powerful enough to reliably do this. You need a parser that actually understands Java.

You should use one of these:

  • ANTRL with a Java Grammar
  • javaparser (a Java source code parser)
  • javacc (Java compiler compiler, the javaparser above is based on this)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜