package _468; import java.util.regex.Pattern; class Solution { public String validIPAddress(String IP) { Pattern ipv4 = Pattern.compile("^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d).(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d).(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d).(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$"); Pattern ipv6 = Pattern.compile("^[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}:[a-fA-F0-9]{1,4}$"); boolean isV4 = ipv4.matcher(IP).matches(); boolean isV6 = ipv6.matcher(IP).matches(); if (isV4) { return "IPv4"; } else if (isV6) { return "IPv6"; } return "Neither"; } private static void testValidIPAddress(String IP) { Solution solution = new Solution(); System.out.println(solution.validIPAddress(IP)); } public static void main(String[] args) { testValidIPAddress("172.16.254.1"); testValidIPAddress("265.16.254.1"); testValidIPAddress("0001:db8:85a3:0::8AFE:0370:7334"); } }