import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = " # begin capture group 1\n"
+ "\\{\\s+\"name\":[ ]\" # match '\\{' then 1+ whitespace chars, then '\"name\": \"\n"
+ "(\\w+) # match 1+ word chars, save to capture group 1\n"
+ "- # match '-'\n"
+ "(\\w+) # match 1+ word chars, save to capture group 2\n"
+ "- # match '-'\n"
+ "(\\w+) # match 1+ word chars, save to capture group 3\n"
+ "- # match '-'\n"
+ "(\\w+) # match 1+ word chars, save to capture group 4\n"
+ "( # begin capture group 5\n"
+ " \",\\s+\"units\":[ ] # match '\",', then 1+ whitespaces then '\"units\": '\n"
+ " \"\\w+\" # match 1+ word chars\n"
+ " ,\\s+\"value\":[ ] # match ',', then 1+ whitespaces then '\"value\": '\n"
+ " \\d+ # match 1+ digits\n"
+ " \\s+\\} # match 1+ whitespaces then '\"units\": '\n"
+ ") # end capture group 5\n"
+ " # end capture group 1\n"
+ "(?! # begin negative lookahead\n"
+ " .* # match 0+ chars\n"
+ " \\{\\s+\"name\":[ ]\" # match '\\{' then 1+ whitespace chars then '\"name\": ' then '\"'\n"
+ " \\1_ # match contents of capture group 1 then '_'\n"
+ " \\2_ # match contents of capture group 2 then '_'\n"
+ " \\3_ # match contents of capture group 3 then '_'\n"
+ " \\4 # match contents of capture group 4\n"
+ " \\5 # match contents of capture group 5\n"
+ ") # end of negative lookahead \n"
+ "| # or\n"
+ "\\{\\s+\"name\":[ ]\" # match '\\{' then 1+ whitespace chars, then '\"name\": \"\n"
+ "\\w+ # match 1+ word chars\n"
+ "_ # match '_'\n"
+ "\\w+ # match 1+ word chars\n"
+ "_ # match '_'\n"
+ "\\w+ # match 1+ word chars\n"
+ "_ # match '_'\n"
+ "\\w+ # match 1+ word chars\n"
+ "(?5) # execute code constructing capture group 6\n";
final String string = "{\n"
+ " \"body\": {\n"
+ " \"metricsArray\": [\n"
+ " {\n"
+ " \"name\": \"free-aa-bb2-123x123Profiles\",\n"
+ " \"units\": \"profiles\",\n"
+ " \"value\": 14\n"
+ " },\n"
+ " {\n"
+ " \"name\": \"free_aa_bb2_123x123Profiles\",\n"
+ " \"units\": \"profiles\",\n"
+ " \"value\": 14\n"
+ " }\n"
+ " ],\n"
+ " \"name\": \"regionxxx\",\n"
+ " \"timeStamp\": \"2022-01-20T04:58:29.875Z\"\n"
+ " }\n"
+ "}\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL | 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