Get Programming Language Keywords By Using Regular Expression in Java
We can use regular expression to get all Java keywords in a program. The key is using word boundary correctly. For example, given "static staticField", the first word should be recognized as a keyword but the second should not.
Here is the code:
package regex; 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(exp); Matcher m = p.matcher(target); while(m.find()){ System.out.println("|"+m.group()+"|"); System.out.println(m.start()); System.out.println(m.end()); } } } |
Output:
|static| 0 6 |public| 7 13
Check out Boundary Matcher for more examples.
<pre><code> String foo = "bar"; </code></pre>
-
yes yes