简体   繁体   中英

Which regular expression can be used to recognize keywords in java?

I want to match keywords like if,else,new,and..etc.Please suggest an appropriate regular expression to match them.

I have tried with

(((\\s)+(when|then|end|and))+(\\s|$))|rule|if|else|(new+(\\s)) 

but it is not working properly.

If you have a list a Java keywords, then you can turn it into a regex that matches those keywords like this (in principle - the following isn't meant to be used as actual code, just to illustrate how it works):

"\\b(?:" + "if" + "|" + "for" + "|" + ... + "|" + "new" + "|" + "static" + ")\\b"

That regex uses word boundary anchors to make sure it doesn't match if in the word knife , for example.

It has no concept of semantics, though, so unless you have already done some parsing to separate comments or strings etc. from the "command parts" of the source code, then you will find matches in places where they are not necessarily being used as keywords.

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