Java Regex – Hacker Rank Solution

Java Regex - Hacker Rank Solution
Java Regex – Hacker Rank Solution

Problem :

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. Use the following definition of an IP address:

IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.

Some valid IP address:

Some invalid 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 . The string should contain the correct regular expression.

(MyRegex class MUST NOT be public)

Sample Input

Sample Output


Java Regex – Hacker Rank 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(;
            String IP =;
            System.out.println(IP.matches(new MyRegex().pattern));
     [01]?\\d{1,2}   matches numbers 0-199.
     2[0-4]\\d       matches numbers 200-249
     25[0-5]         matches numbers 250-255
class MyRegex {
    String num = "([01]?\\d{1,2}|2[0-4]\\d|25[0-5])";
    String pattern = num + "." +  num + "." +  num + "." + num;

Disclaimer: The above Problem (Java Regex) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Tags: HackerRank Online Judge Solution, HackerRank OJ Solution list, HackerRank Problems Solution, HackerRank solver, HackerRank all problem solution list, HackerRank solution in java, Hackerrank Java Solution, Hackerrank – Java Solution – Java Regex Solution, Hackerrank Online Judge Solution, Hackerrank – Java Solutions,

Leave a Comment