I have a set of IP adresses with special format, which I have to check if it matches the needed regex pattern. My pattern right now looks like this:
private static final String FIRST_PATTERN = "([0-9]{1,3}\\\\{2}?.[0-9]{1,3}\\\\{2}?.[0-9]{1,3}\\\\{2}?.[0-9]{1,3})";
This pattern allows me to check strict IP adresses and recognize the pattern, when IP adresses are static, for example: "65\\.33\\.42\\.12" or "112\\.76\\.39\\.104, 188\\.35\\.122\\.148".
I should, however, also be able to look for some non static IP's, like this:
"155\\.105\\.178\\.(8[1-9]|9[0-5])"
or this:
"93\\.23\\.75\\.(1(1[6-9]|2[0-6])), 113\\.202\\.167\\.(1(2[8-9]|[3-8][0-9]|9[0-2]))"
I have tried to do it in several ways, but it always gives "false", when try to match those IP's. I searched for this solution for a decent amount of time and I cannot find it and also cannot wrap my head around of how to do it myself. Is there anyone who can help me?
UPDATE Whole code snippet:
public class IPAdressValidator {
Pattern pattern;
Matcher matcher;
private static final String FIRST_PATTERN = "([0-9]{1,3}\\\\{2}?.[0-9]{1,3}\\\\{2}?.[0-9]{1,3}\\\\{2}?.[0-9]{1,3})";
public IPAdressValidator() {
pattern = Pattern.compile(FIRST_PATTERN);
}
public CharSequence validate(String ip) {
matcher = pattern.matcher(ip);
boolean found = matcher.find();
if (found) {
for (int i = 0; i <= matcher.groupCount(); i++) {
int groupStart = matcher.start(i);
int groupEnd = matcher.end(i);
return ip.subSequence(groupStart, groupEnd);
}
}
return null;
}
}
and my Main:
public class Main {
public static void main(String[] args) {
IPAdressValidator validator = new IPAdressValidator();
String[] ips =
"53\\\\.22\\\\.14\\\\.43",
"123\\\\.55\\\\.19\\\\.137",
"93\\.152\\.199\\.1",
"(93\\.199\\.(?:1(?:0[6-7]))\\.(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])))",
"193\\\\.163\\\\.100\\\\.(8[1-9]|9[0-5])",
"5\\\\.56\\\\.188\\\\.130, 188\\\\.194\\\\.180\\\\.138, 182\\\\.105\\\\.24\\\\.15",
"188\\\\.56\\\\.147\\\\.193,41\\\\.64\\\\.202\\\\.19"
};
for (String ip : ips) {
System.out.printf("%20s: %b%n", ip, validator.validate(ip));
}
}
}