This is a Hackerrank java series
In this series we will learn java with full implementation
#dsaforbeginners #tech #coding #codinglife #programmer
In this video, we will see Regular Expression in Java. We will solve a Java Regex problem from HackerRank.
Step A: Regex for ONE number between 0 and 255
Numbers 0 to 255 can be divided into groups:
Group 1: 250 to 255
Regex: 25[0-5]
Explanation:
25 is fixed
[0-5] means one digit from 0 to 5
Group 2: 200 to 249
Regex: 2[0-4]\d
Explanation:
starts with 2
second digit is 0 to 4
\d means any digit 0 to 9
So it matches 200 to 249.
Group 3: 0 to 199
Regex: [01]?\d\d?
Breakdown:
[01]? means optional 0 or 1 at the start
\d one digit required
\d? another digit optional
So it matches: 0, 7, 99, 100, 199
and also 00, 000, 001 (leading zeros). HackerRank accepts this.
One octet:
(25[0-5]|2[0-4]\d|[01]?\d\d?)
The symbol | means OR.
Anchors:
^ = start of string
$ = end of string
Final regex:
^(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?).(25[0-5]|2[0-4]\d|[01]?\d\d?)$
Java string escaping (VERY IMPORTANT)
In Java strings: backslash \ must be written as \
So:
\d becomes \d
. becomes \.
Code:
class MyRegex {
String pattern;
text
MyRegex(){
String ptrn = "(25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)";
pattern = "^"+ ptrn + "\\\\." + ptrn + "\\\\." + ptrn + "\\\\." + ptrn + "$";
}
}
Quick tests:
192.168.1.1 : true
256.1.1.1 : false (256 is not in 0 to 255)
000.12.12.034 : true
121.234.12.12 : true
23.45.12.56 : true
000.12.234.23.23 : false (has 5 parts)
666.666.23.23 : false (666 is greater than 255)