import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:(?>([a-f0-9]{1,4})(?>:(?1)){7}|(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?4)){3}))$";
final String string = "/*These should be valid*/\n\n"
+ "{Initial address}\n"
+ "2001:0db8:0000:0000:0000:ff00:0042:8329\n\n"
+ "{After removing all leading zeroes}\n"
+ "2001:db8:0:0:0:ff00:42:8329\n\n"
+ "{After omitting consecutive sections of zeroes}\n"
+ "2001:db8::ff00:42:8329\n\n"
+ "{The loopback address}\n"
+ "0000:0000:0000:0000:0000:0000:0000:0001\n\n"
+ "{The loopback address be abbreviated to ::1 by using both rules}\n"
+ "::1\n\n"
+ "{4 other valid test cases}\n"
+ "::FFFF:129.144.52.38\n"
+ "::129.144.52.38\n"
+ "::FFFF:d\n"
+ "1080:0:0:0:8:800:200C:417A\n\n"
+ "/*These 4 should be invalid*/\n"
+ "::FFFF:d.d.d\n"
+ "::FFFF:d.d\n"
+ "::d.d.d\n"
+ "::d.d";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | 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