在Java中使用正则表达式获取关键字

我们可以利用正则表达式获取一个程序中的所有关键字。关键是正确使用单词边界。比如,给出“static staticFiled”,第一个单词应该被认为是关键字,而第二个不是。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.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, "|");
 
		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());
		}
	}
}

你可能感兴趣的:(Java,代码)