Goldman Sachs Interview Question
Software Engineer / Developerssmall correction
String regExp = "[0-2]?[0-5]?[0-5]?\\.[0-2]?[0-5]?[0-5]?\\.[0-2]?[0-5]?[0-5]?\\.[0-2]?[0-5]?[0-5]?";
return ipAdd.matche(regExp);
the regex above will work for REAL IP addresses ( except for 0.*.*.*) but the question say that the IP is passed as String so 000.000.000.000 will not be matched.
by modifying the above regex you get this: ^([0-9]|0[0-9][0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|0[0-9][0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$ which should work for all IP formats (REAL and string ones).
By REAL I mean 000.000.000.000 -> 0.0.0.0
String ipAdd = "123.123.123.123";
- Bobby March 04, 2010sysout(verifyIpAddress(ipAdd))
boolean verifyIpAddress(String ipAdd) {
String regExp = "[0-2][0-5][0-5]\\.[0-2][0-5][0-5]\\.[0-2][0-5][0-5]\\.[0-2][0-5][0-5]";
return ipAdd.matches(regExp);
}