In a Java application, we can use regular expressions to get all the Java keywords. Then the key is to use the word boundaries correctly. For example: In the string "Static Staticfield", the first word should be recognized as a keyword, but the second cannot.
This is the code that gets the Java program keyword:
Package Hxl.programmer.path;import Java.util.regex.matcher;import Java.util.regex.pattern;import Org.apache.commons.lang3.StringUtils; public class Regtest {public static void main (string[] args) {String keystring = ' abstract assert ' Boolean break ' byte case Catch "+" char class const continue default do double else enum "+" extends false final finally float for Goto if implemen TS "+" Import instanceof int interface long native new null "+" package private protected public return short static "+" STRICTFP Super Switch synchronized this throw throws true "+" transient try void volatile while "; String[] keys = Keystring.split (""); String KEYSTR = Stringutils.join (keys, "|"); System.out.println (KEYSTR); String regex = "\\b (" +keystr+ ") \\b"; String target = "static public staticpublic void Main ()"; Pattern p = pattern.compile (regex); Matcher m = p.matcher (target); while (M.find ()) {System.out.println ("|") +m.group () + "|"); System.out.println (M.start ()); System.out.println (M.end ());}}}
The output is as follows:
abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|extends| false|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|native|new|null|package| private|protected|public|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|true| transient|try|void|volatile|while|static|06|public|713|void|2731
Friendship Hint: Above stringutils is need Apache of an open source jar package, I use the name is Commons-lang3-3.3.2.jar, everybody can go to official website to download, below is address:
http://commons.apache.org/proper/commons-lang/download_lang.cgi
Use regular expressions to get all the keywords in Java