-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaRegex.java
More file actions
40 lines (29 loc) · 808 Bytes
/
Copy pathJavaRegex.java
File metadata and controls
40 lines (29 loc) · 808 Bytes
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
28
29
30
31
32
33
34
35
36
37
38
39
40
/*Write a regex pattern to validate an IPv4 address.
A valid IP address:
Has 4 parts separated by .
Each part is between 0 and 255
Leading zeros are allowed
Example:
121.234.12.12 -> true
666.666.23.23 -> false*/
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();
// Check whether IP matches the regex pattern
System.out.println(IP.matches(new MyRegex().pattern));
}
in.close();
}
}
class MyRegex
{
// Matches a valid IPv4 address
// Range of each part: 0 - 255
String pattern =
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" +
"(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}";
}