简体   繁体   中英

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

I created a regular expression bellow to do this. But 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM