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.
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));
}
}
}
class MyRegex{
String pattern="^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
}
//Write your code here
/* ^: Asserts the start of a line.
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.): This part of the pattern matches the first three segments of the IP address (octets) followed by a dot. It consists of three alternatives separated by the | symbol:
25[0-5]: Matches numbers from 250 to 255.
2[0-4][0-9]: Matches numbers from 200 to 249.
[01]?[0-9][0-9]?: Matches numbers from 0 to 199. The [01]? part allows for single-digit numbers or numbers starting with 0.
{3}: Specifies that the previous group (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. should occur exactly three times, representing the first three octets of the IP address.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?): This part matches the fourth segment of the IP address (last octet) without a trailing dot. It follows the same pattern as the first three octets.
$: Asserts the end of a line. */
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Regex
You are viewing a single comment's thread. Return to all comments →
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner;
class Solution{
} class MyRegex{ String pattern="^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
} //Write your code here /* ^: Asserts the start of a line.
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.): This part of the pattern matches the first three segments of the IP address (octets) followed by a dot. It consists of three alternatives separated by the | symbol: 25[0-5]: Matches numbers from 250 to 255. 2[0-4][0-9]: Matches numbers from 200 to 249. [01]?[0-9][0-9]?: Matches numbers from 0 to 199. The [01]? part allows for single-digit numbers or numbers starting with 0.
{3}: Specifies that the previous group (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\. should occur exactly three times, representing the first three octets of the IP address. (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?): This part matches the fourth segment of the IP address (last octet) without a trailing dot. It follows the same pattern as the first three octets. $: Asserts the end of a line. */