HackerRank Java Regex problem solution YASH PAL, 31 July 2024 In this HackerRank Java Regex problem in the java programming language, Write a class called MyRegex which will contain a string pattern. You need to write a regular expression and assign it to the pattern such that it can be used to validate an IP address. In this problem you will be provided strings containing any combination of ASCII characters. You have to write a regular expression to find the valid IPs. Just write the MyRegex class which contains a String pattern. The string should contain the correct regular expression. HackerRank Java Regex problem solution. import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } } } //Write your code here class MyRegex { String ip0to255 = "(\d{1,2}||(0|1)\d{2}||2[0-4]\d||25[0-5])"; public String pattern = ip0to255 + "\." + ip0to255 + "\." + ip0to255 + "\." + ip0to255; } Second solution import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } } } //Write your code here class MyRegex { public String pattern = "((\d|\d\d|[0-1]\d\d|2[0-4][0-9]|25[0-5])\.){3}(\d|\d\d|[0-1]\d\d|2[0-4][0-9]|25[0-5])"; } A solution in java8 programming. import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNext()){ String IP = in.next(); System.out.println(IP.matches(new MyRegex().pattern)); } } } //Write your code here class MyRegex { public String pattern = "((\d|\d\d|[0-1]\d\d|2[0-4][0-9]|25[0-5])\.){3}(\d|\d\d|[0-1]\d\d|2[0-4][0-9]|25[0-5])"; } coding problems hackerrank solutions java