在一个Java应用程序中,我们可以用正则表达式可以得到所有的java关键字。那么关键就是正确地使用词边界。例如:在"static staticField"这个字符串当中,第一个单词应该被当作关键字识别,但是第二个不能。
这是得到Java程序关键字的代码:
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 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";
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());
}
}
}
输出如下:
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|
0
6
|public|
7
13
|void|
27
31
友情提示:上面的StringUtils是需要Apache的一个开源Jar包,我用的名字是commons-lang3-3.3.2.jar,大家可以去官网下载,下面是地址:
http://commons.apache.org/proper/commons-lang/download_lang.cgi