4
\$\begingroup\$

I'm toying with Regexes to parse IP Addresses. I've got it to test for anything over 255:

public static boolean isIpAddress(String address)
{
    String regex = "^((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))(\\.((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))){3}$";
    try{
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(address);

        return m.find();
    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return false;
}

Is there a more efficient way to write that regex?

I understand that I could probably run something like this:

String[] addressChunks = address.split(".");
String regex = "^((25[0-5])|(((1[0-9]|2[0-4])|[1-9])?[0-9]))$";
Pattern p = Pattern.compile(regex);
for(String s: addressChunks)
{
    Matcher m = p.matcher(s);
    if(!m.find(s))
    {
      return false;
    }
}
return true;

But I'd rather keep it to one line of regex and compare it all instead of doing a split.

\$\endgroup\$
2
\$\begingroup\$

Try:

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|$)){4}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Why the [01]? in the middle? \$\endgroup\$ – CBredlow Mar 29 '17 at 18:54
  • \$\begingroup\$ The 0 accommodates for leading 0s: 192.168.002.011 - it's uncommon but technically valid. 1 is for numbers in the 100 range. ? makes both the 0 and the 1 optional. \$\endgroup\$ – RACC Mar 30 '17 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.