Solution.java 1.1 KB

1234567891011121314151617181920212223242526272829
  1. package _468;
  2. import java.util.regex.Pattern;
  3. class Solution {
  4. public String validIPAddress(String IP) {
  5. 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)$");
  6. 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}$");
  7. boolean isV4 = ipv4.matcher(IP).matches();
  8. boolean isV6 = ipv6.matcher(IP).matches();
  9. if (isV4) {
  10. return "IPv4";
  11. } else if (isV6) {
  12. return "IPv6";
  13. }
  14. return "Neither";
  15. }
  16. private static void testValidIPAddress(String IP) {
  17. Solution solution = new Solution();
  18. System.out.println(solution.validIPAddress(IP));
  19. }
  20. public static void main(String[] args) {
  21. testValidIPAddress("172.16.254.1");
  22. testValidIPAddress("265.16.254.1");
  23. testValidIPAddress("0001:db8:85a3:0::8AFE:0370:7334");
  24. }
  25. }