import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^\n"
+ "School\\s*=\\s*(?P<school_name>.+)\n"
+ "(?P<school_content>[\\s\\S]+?)\n"
+ "(?=^School|\\Z)";
final String string = "Sample text\n\n"
+ "A selection of students from Riverdale High and Hogwarts took part in a quiz. This is a record of their scores.\n\n"
+ "School = Riverdale High\n"
+ "Grade = 1\n"
+ "Student number, Name\n"
+ "0, Phoebe\n"
+ "1, Rachel\n\n"
+ "Student number, Score\n"
+ "0, 3\n"
+ "1, 7\n\n"
+ "Grade = 2\n"
+ "Student number, Name\n"
+ "0, Angela\n"
+ "1, Tristan\n"
+ "2, Aurora\n\n"
+ "Student number, Score\n"
+ "0, 6\n"
+ "1, 3\n"
+ "2, 9\n\n"
+ "School = Hogwarts\n"
+ "Grade = 1\n"
+ "Student number, Name\n"
+ "0, Ginny\n"
+ "1, Luna\n\n"
+ "Student number, Score\n"
+ "0, 8\n"
+ "1, 7\n\n"
+ "Grade = 2\n"
+ "Student number, Name\n"
+ "0, Harry\n"
+ "1, Hermione\n\n"
+ "Student number, Score\n"
+ "0, 5\n"
+ "1, 10\n\n"
+ "Grade = 3\n"
+ "Student number, Name\n"
+ "0, Fred\n"
+ "1, George\n\n"
+ "Student number, Score\n"
+ "0, 0\n"
+ "1, 0\n\n\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.COMMENTS);
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