这是得到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
http://commons.apache.org/proper/commons-lang/download_lang.cgi
原文地址:http://blog.csdn.net/xlinsist/article/details/42913333