Java - Clear Regex Solution


  • 0
    M
       public String validIPAddress(String IP) {
            
            String singleIPv4 = "([0-9]|[1-9][0-9]|[1][0-9]{2}|[2][0-5]{2})";
            String IPv4 = String.format("(%s\\.){3}%s", singleIPv4,singleIPv4);
    	if (IP.matches(IPv4))
                  return "IPv4";
    		
    	String singleLetter = "[A-Fa-f0-9]";
    	String singleIPv6 = String.format("(%s{1,4}|[0]%s{0,3})", singleLetter,singleLetter);
    	String IPv6 = String.format("(%s:){7}%s", singleIPv6,singleIPv6);
    	
            if (IP.matches(IPv6))
                    return "IPv6";
            return "Neither";
            
            
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.