用正则表达式得到Java中所有的关键字

一个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

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...