import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^@ heading2$[\\s\\S]*?^(?:field2: \\\"?((?<=\\\")[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*(?=\\\"$)|(?<!\\\").*(?!\\\")$)\\\"?$|)?$[\\s\\S]*?(?=@ [^\\s]*?|\\Z)";
final String string = "@ heading1\n"
+ "field1: \"single-line strings are quoted only sometimes.\"\n"
+ "field2: \"strings that span\n"
+ "multiple lines\n"
+ "are always quoted.\"\n"
+ "field3: this single-line string is unquoted.\n\n"
+ "@ heading2\n"
+ "field1: field names can be repeated among headings.\n"
+ "field2: \"Regex is harder when I add an\n"
+ "@ in a multi-line string, or if I add\n"
+ "backslash-escaped characters like \\\" and \\'.\n\n"
+ "What happens if I have an empty line in a string?\n\n"
+ "Also,\n"
+ "[this line]\n"
+ "isn't actually a section.\"\n"
+ "field3: this field comes after field2\n"
+ "[sectionname]\n"
+ "field1: the same field name under a different section.\n"
+ "[anothersection]\n"
+ "field1: a second section under the same heading\n"
+ "field4: field number four\n\n"
+ "@ heading3\n"
+ "field1: value value value value value\n"
+ "field2: \"quoted string\n"
+ "quoted string\n"
+ "quoted string\"\n"
+ "unique: unique field name";
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