Problem Statement
A description of the problem can be found on Hackerrank.
Solution
IP4 regex:
\b(((2[0-5][0-5])|(1[0-9][0-9])|(\b[1-9][0-9]\b)|(\b\d\b))\.){3}((2[0-5][0-5])|(1[0-9][0-9])|(\b[1-9][0-9]\b)|(\b\d\b))\b
IP6 regex:
([a-f0-9]{1,4}:){7}\b[0-9a-f]{1,4}\b
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.*; public class IPAddressValidation { private static final String IP6_PATTERN = "([a-f0-9]{1,4}:){7}\\b[0-9a-f]{1,4}\\b"; private static final String IP4_PATTERN = "\\b(((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\.){3}((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\b"; public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { System.out.println(ipValidation(stdin.nextLine())); } stdin.close(); } private static String ipValidation(String address) { if(address.matches(IP6_PATTERN)) return "IPv6"; else if(address.matches(IP4_PATTERN)) return "IPv4"; else return "Neither"; } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
'use strict'; const IP6_PATTERN = "([a-f0-9]{1,4}:){7}\\b[0-9a-f]{1,4}\\b"; const IP4_PATTERN = "\\b(((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\.){3}((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\b"; const processData = input => { let lines = input.split('\n').slice(1); let ipValidation = address => { if(address.match(new RegExp(IP4_PATTERN))) { return "IPv4"; } else if(address.match(new RegExp(IP6_PATTERN))) { return "IPv6"; } else { return "Neither"; } }; let validations = lines.map(ipValidation); console.log(validations.join('\n')); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import scala.io.Source object IPAddressValidation extends App { private[this] val IP6_PATTERN = "([a-f0-9]{1,4}:){7}\\b[0-9a-f]{1,4}\\b" private[this] val IP4_PATTERN = "\\b(((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\.){3}((2[0-5][0-5])|(1[0-9][0-9])|(\\b[1-9][0-9]\\b)|(\\b\\d\\b))\\b" val lines = Source.stdin.getLines().drop(1) val validation = lines.map(ipValidation) println(validation.mkString("\n")) def ipValidation(address: String): String = { if(address.matches(IP6_PATTERN)) "IPv6" else if(address.matches(IP4_PATTERN)) "IPv4" else "Neither" } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
tests = gets.chomp.to_i tests.times do input = gets.chomp.to_s if input =~ /\b(((2[0-5][0-5])|(1[0-9][0-9])|(\b[1-9][0-9]\b)|(\b\d\b))\.){3}((2[0-5][0-5])|(1[0-9][0-9])|(\b[1-9][0-9]\b)|(\b\d\b))\b/ puts "IPv4" elsif input =~ /([a-f0-9]{1,4}:){7}\b[0-9a-f]{1,4}\b/ puts "IPv6" else puts "Neither" end end |