微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用正则表达式得到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

原文地址:https://www.jb51.cc/regex/360834.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐