import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:\\t| )*(?:#|%|;|//|--|REM|C|!) (?:#{64} (.*)|#{32} (.*)|#{16} (.*)|#{8} (.*)|#{4} (.*)|#{2} (.*))$";
final String string = "Valid comments that start with \"#\":\n\n"
+ "# ################################################################ First Level\n"
+ "# ################################ Second Level\n"
+ "# ################ Third level\n"
+ "# ######## Fourth Level\n"
+ "# #### Fifth level\n"
+ "# ## Sixth level\n\n"
+ "Valid comments that start with different characters:\n\n"
+ "// ################################################################ 1st Level\n"
+ "; ################################ 2nd Level\n"
+ "REM ################ 3rd level\n"
+ "C ######## 4th Level\n"
+ "% #### 5th level\n"
+ "-- ## 6th level\n\n"
+ "Valid comments that start with spaces or tabs:\n"
+ " # ################################################################ 1st level\n"
+ " ; ################################ 2nd Level\n\n"
+ "Invalid comments:\n\n"
+ "################################################################ No initial character\n"
+ "; ################################################ Hashes not a power of 2\n"
+ "@ ################ Character not recognized\n"
+ "C ########No space after hashes\n"
+ "% %%%%%%%% No hashes\n"
+ ". # #### Period before spaces\n"
+ " ;#### No space after character";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html