We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;importjava.util.regex.Pattern;importjava.util.regex.Matcher;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);intt=scanner.nextInt();scanner.nextLine();Stringu="(25[0-5]|2[0-4]\\d|1?\\d?\\d)";//0 to 255Stringregex_ipv4=String.format("^(%s\\.){3}%s$",u,u);//u.u.u.uStringv="[a-fA-F0-9]{1,4}";//4 hexadecimal digitsStringregex_ipv6=String.format("^(%s\\:){7}%s$",v,v);//v:v:v:v:v:v:v:v (8 groups)Patternpattern_ipv4=Pattern.compile(regex_ipv4);Patternpattern_ipv6=Pattern.compile(regex_ipv6);for(inti=0;i<t;i++){Stringstr=scanner.nextLine();Matchermatcher_ipv4=pattern_ipv4.matcher(str);Matchermatcher_ipv6=pattern_ipv6.matcher(str);if(matcher_ipv4.find())System.out.println("IPv4");elseif(matcher_ipv6.find())System.out.println("IPv6");elseSystem.out.println("Neither");}}}/*---------- v = "[a-fA-F0-9]{1,4}" ---------------4 hexadecimal digits.Hexadecimal means either using a-f or 0-9ff translates to 00ff. So no of digits can be either 1,2,3 or 4. So use {1,4}---------- u = "(25[0-5]|2[0-4]\\d|1?\\d?\\d)" ---------------Means 0 to 2553 digit combinations: 25[0-5] or 2[0-4][0-9] or 1[0-9][0-9] 2 digit combinations: [0-9][0-9]1 digit combinations: [0-9]Combining 1 digit and 2 digit combinations: becomes: [0-9]?[0-9] Combine this with 1[0-9][0-9] : becomes : 1?[0-9]?[0-9]So final set of combinations : becomes: 25[0-5] or 2[0-4][0-9] or 1?[0-9]?[0-9]*/
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
IP Address Validation
You are viewing a single comment's thread. Return to all comments →
Java 15