Mega Code Archive

 
Categories / Java Tutorial / Regular Expressions
 

Match Java source file and file and class name

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExpExample {   public static void main(String args[]) {     String unadornedClassRE = "^\\s*class (\\w+)";     String doubleIdentifierRE = "\\b(\\w+)\\s+\\1\\b";     Pattern classPattern = Pattern.compile(unadornedClassRE);     Pattern doublePattern = Pattern.compile(doubleIdentifierRE);     Matcher classMatcher, doubleMatcher;     String line = " class MainClass";     classMatcher = classPattern.matcher(line);     doubleMatcher = doublePattern.matcher(line);     if (classMatcher.find()) {       System.out.println("The class [" + classMatcher.group(1) + "] is not public");     }     while (doubleMatcher.find()) {       System.out.println("The word \"" + doubleMatcher.group(1) + "\" occurs twice at position "           + doubleMatcher.start());     }   } }