most easy java regex solution


  • 0
    G
    public class Solution {
        public String validIPAddress(String IP) {
            if(isIP4(IP)){
                return "IPv4";
            }
            
            if(isIP6(IP)){
                return "IPv6";
            }
            
            return "Neither";
            
        }
        
        public boolean isIP4(String IP){
            String regax = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
            if(IP.matches(regax)){
                return true;
            }
            return false;
        }
        
        public boolean isIP6(String IP){
            String regax = "([0-9a-fA-F]|[0-9a-fA-F]{2}|[0-9a-fA-F]{3}|[0-9a-fA-F]{4})(\\:([0-9a-fA-F]|[0-9a-fA-F]{2}|[0-9a-fA-F]{3}|[0-9a-fA-F]{4})){7}";
            if(IP.matches(regax)){
                return true;
            }
            return false;
            
        }
    }

Log in to reply
 

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