import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?(DEFINE)\n"
+ " (?<quote>['\"])\n"
+ " (?<pair>\n"
+ " (?>\n"
+ " \\w+\n"
+ " |(?:\n"
+ " (?<pairQuote>(?"e))[^'\"]+?\\k<pairQuote>\n"
+ " )\n"
+ " )\n"
+ " \\s*\\:\n"
+ " )\n"
+ " (?<string>\n"
+ " (?<stringQuote>(?"e))[\\S\\s]*?(?<!\\\\)\\k<stringQuote>\n"
+ " )\n"
+ " (?<integer>\\-?\\d+(?:\\.\\d+)?(?:e[-+]\\d+)?)\n"
+ " (?<scalar>true|false|null|(?&integer))\n"
+ " (?<elements>\n"
+ " \\s*(?&value)\n"
+ " (?(R&array)|(?>(?:\\s*\\,(?&elements))|\\s*))\n"
+ " )\n"
+ " (?<array>\\[(?>(?&elements)|\\s*)\\])\n"
+ " (?<value>\n"
+ " (?&object)\n"
+ " |(?&string)\n"
+ " |(?&scalar)\n"
+ " |(?&array)\n"
+ " )\n"
+ " (?<members>\n"
+ " \\s*(?&pair)\\s*(?&value)\n"
+ " (?(R&object)|(?>(?:\\s*\\,(?&members))|\\s*))\n"
+ " )\n"
+ " (?<object>\\{(?&members)?\\})\n"
+ ")\n\n"
+ "\\A(?&object)\\Z";
final String string = "{\"menu\": {\n"
+ " \"header\": \"SVG Viewer\",\n"
+ " \"items\": [\n"
+ " {\"id\": \"Open\"},\n"
+ " {\"id\": \"OpenNew\", \"label\": \"Open New\"},\n"
+ " null,\n"
+ " {\"id\": \"ZoomIn\", \"label\": \"Zoom In\"},\n"
+ " {\"id\": \"ZoomOut\", \"label\": \"Zoom Out\"},\n"
+ " {\"id\": \"OriginalView\", \"label\": \"Original View\"},\n"
+ " null,\n"
+ " {\"id\": \"Quality\"},\n"
+ " {\"id\": \"Pause\"},\n"
+ " {\"id\": \"Mute\"},\n"
+ " null,\n"
+ " {\"id\": \"Find\", \"label\": \"Find...\"},\n"
+ " {\"id\": \"FindAgain\", \"label\": \"Find Again\"},\n"
+ " {\"id\": \"Copy\"},\n"
+ " {\"id\": \"CopyAgain\", \"label\": \"Copy Again\"},\n"
+ " {\"id\": \"CopySVG\", \"label\": \"Copy SVG\"},\n"
+ " {\"id\": \"ViewSVG\", \"label\": \"View SVG\"},\n"
+ " {\"id\": \"ViewSource\", \"label\": \"View Source\"},\n"
+ " {\"id\": \"SaveAs\", \"label\": \"Save As\"},\n"
+ " null,\n"
+ " {\"id\": \"Help\"},\n"
+ " {\"id\": \"About\", \"label\": \"About Adobe CVG Viewer...\"}\n"
+ " ],\n"
+ " \"test\": [\n"
+ " \"Some value\",\n"
+ " 4,\n"
+ " null,{}\n"
+ " ],\n"
+ " \"empty_array\":[-0.34E+4]\n"
+ "}}";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | 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