import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^\n"
+ "(?(DEFINE)\n"
+ " (?<hex4>[0-9A-Fa-f]{1,4})\n"
+ " (?<hex4_>(?&hex4):)\n"
+ " (?<_hex4>:(?&hex4))\n"
+ " (?<byte>\n"
+ " (25[0-5])|(2[0-4]\\d)|(1\\d{2})|([1-9]\\d)|\\d\n"
+ " )\n"
+ " (?<ipv4>\n"
+ " ((?&byte)\\.){3}(?&byte)\n"
+ " )\n"
+ ")\n"
+ "(((?&hex4_){7}(?&hex4))\n"
+ "|((?&hex4_){5}(?&_hex4))\n"
+ "|((?&hex4_){4}(?&_hex4){1,2})\n"
+ "|((?&hex4_){3}(?&_hex4){1,3})\n"
+ "|((?&hex4_){2}(?&_hex4){1,4})\n"
+ "|((?&hex4_){1}(?&_hex4){1,5})\n"
+ "|(:(?&_hex4){1,6})\n"
+ "|((?&hex4_){1,6}:)\n"
+ "|((?&hex4_){6}(?&ipv4))\n"
+ "|((?&hex4_){3}(?&_hex4):(?&ipv4))\n"
+ "|((?&hex4_){2}(?&_hex4){1,2}:(?&ipv4))\n"
+ "|((?&hex4_){1}(?&_hex4){1,3}:(?&ipv4))\n"
+ "|((?&hex4_){1,4}:(?&ipv4))\n"
+ "|(:(?&_hex4){0,4}:(?&ipv4))\n"
+ ")$";
final String string = ";valid\n"
+ "2001:db8:0:0:0:0:2:1\n"
+ "2001:db8::2:1\n"
+ "2001:db8:0:1:1:1:1:1\n"
+ "2001:db8:a0b:12f0::1\n"
+ "2001:0db8:0a0b:12f0:0000:0000:0000:0001\n"
+ "3731:54:65fe:2::a7\n"
+ "::10.0.0.3\n"
+ "::ffff:0:10.0.0.3\n"
+ "0064:ff9b:0000:0000:0000:0000:18.52.86.120\n"
+ "0064:ff9b::0000:18.52.86.120\n"
+ "0064:ff9b::18.52.86.120\n\n"
+ ";invalid\n"
+ "2001:db8::1:1:1:1:1\n"
+ "10.0.0.3\n"
+ "::256.127.0.1\n"
+ "::127.0.0.01\n"
+ "::127.0.0\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