1. 程式人生 > >用正則表示式得到Java中所有的關鍵字

用正則表示式得到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