import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))(?<!127)(?<!^10)(?<!^0)\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!192\\.168)(?<!172\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!\\.255$)$";
final String string = "# Invalid IPs:\n"
+ "999.999.999.999.\n"
+ "108.0.0.01\n"
+ "0.1.2.3\n"
+ "00.0000.00.00\n"
+ "192.168.l.1\n"
+ "912.456.123.123\n"
+ ".3.3.3.0\n"
+ "192.168.o.0\n\n"
+ "# Local IPs:\n"
+ "172.16.0.9\n"
+ "172.16.4.1\n"
+ "172.17.1.1\n"
+ "127.0.0.2\n"
+ "10.0.1.5\n"
+ "10.0.0.1\n"
+ "10.155.155.155\n"
+ "10.255.255.254\n"
+ "172.16.0.4\n"
+ "172.16.0.1\n"
+ "172.17.1.1\n"
+ "172.31.254.254\n"
+ "192.168.1.2\n"
+ "192.168.254.0\n"
+ "169.254.2.2\n\n"
+ "# Broadcast IPs:\n"
+ "60.123.247.255\n"
+ "196.168.255.255\n"
+ "10.255.255.255\n"
+ "192.168.255.255\n\n"
+ "# Public IPs:\n"
+ "8.8.8.8\n"
+ "8.8.4.4";
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