Validating IPv4 string in Java
        Posted  
        
            by 
                Mat Banik
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Mat Banik
        
        
        
        Published on 2011-01-03T03:26:40Z
        Indexed on 
            2011/01/03
            3:53 UTC
        
        
        Read the original article
        Hit count: 261
        
Bellow method is validating if string is correct IPv4 address it returns true if it is valid. Any improvements in regex and elegance would be very appreciated:
public static boolean validIP(String ip) {
    if (ip == null || ip.isEmpty()) return false;
    ip = ip.trim();
    if ((ip.length() < 8) & (ip.length() > 15)) return false;
    try {
        Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    } catch (PatternSyntaxException ex) {
        return false;
    }
}
        © Stack Overflow or respective owner