import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?<ip_addr>((\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|((([\\da-fA-F]{1,4}:){7})([\\da-fA-F]{1,4})$|(([\\da-fA-F]{1,4}:){1,6}:)(([\\da-fA-F]{1,4}:){0,4})([\\da-fA-F]{1,4}))|(::[\\da-fA-F]{1,4})|(([\\da-fA-F]{1,4}:){0,7}[\\da-fA-F]{1,4}::)))$";
final String string = "1.2.3.4\n"
+ "01.02.3.4\n"
+ "01.02.03.04\n"
+ "128.101.1.1\n"
+ "128.1.101.101\n"
+ "987.654.321.0\n"
+ "2607:ea00:101:102:103:104:105:106\n"
+ "2607:eA00:abcd:efab:cDeF:0000:0000:0001\n"
+ "fe80::64\n"
+ "ff02::\n"
+ "::1\n"
+ "2001:468::\n\n"
+ "2001::468::4\n"
+ ":::1\n"
+ "2001:410:::\n"
+ "123.123.1a3.313\n"
+ "1.2.3.\n"
+ ".2.3.4\n\n";
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