Given an IP address, the task is to validate this IP address with the help of Regular Expressions.
The 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.
Examples:
Input: str = "000.12.12.034"
Output: True
Input: str = "000.12.234.23.23"
Output: False
Input: str = "121.234.12.12"
Output: True
Input: str = "I.Am.not.an.ip"
Output: False
Approach:
In this article, the IP address is validated with the help of Regular Expressions or Regex. Below are the steps to solve this problem using ReGex:
- Get the string.
- Regular expression to validate an IP address:
// ReGex to numbers from 0 to 255
zeroTo255 -> (\\d{1, 2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])
// ReGex to validate complete IP address
IPAddress -> zeroTo255 + "\\." + zeroTo255
+ "\\." + zeroTo255
+ "\\." + zeroTo255;
- where:
- \d represents digits in regular expressions, same as [0-9]
- \\d{1, 2} catches any one or two-digit number
- (0|1)\\d{2} catches any three-digit number starting with 0 or 1.
- 2[0-4]\\d catches numbers between 200 and 249.
- 25[0-5] catches numbers between 250 and 255.
- Match the string with the Regex. In Java, this can be done using Pattern.matcher().
- Return true if the string matches with the given regex, else return false.
Below is the implementation of the above approach:
Java
import java.util.regex.*;
class IPAddressValidation {
public static boolean isValidIPAddress(String ip)
{
String zeroTo255
= "(\\d{1,2}|(0|1)\\"
+ "d{2}|2[0-4]\\d|25[0-5])" ;
String regex
= zeroTo255 + "\\."
+ zeroTo255 + "\\."
+ zeroTo255 + "\\."
+ zeroTo255;
Pattern p = Pattern.compile(regex);
if (ip == null ) {
return false ;
}
Matcher m = p.matcher(ip);
return m.matches();
}
public static void main(String args[])
{
System.out.println( "Test Case 1:" );
String str1 = "000.12.12.034" ;
System.out.println( "Input: " + str1);
System.out.println(
"Output: "
+ isValidIPAddress(str1));
System.out.println( "\nTest Case 2:" );
String str2 = "121.234.12.12" ;
System.out.println( "Input: " + str2);
System.out.println(
"Output: "
+ isValidIPAddress(str2));
System.out.println( "\nTest Case 3:" );
String str3 = "000.12.234.23.23" ;
System.out.println( "Input: " + str3);
System.out.println(
"Output: "
+ isValidIPAddress(str3));
System.out.println( "\nTest Case 4:" );
String str4 = "I.Am.not.an.ip" ;
System.out.println( "Input: " + str4);
System.out.println(
"Output: "
+ isValidIPAddress(str4));
}
}
|
Output: Test Case 1:
Input: 000.12.12.034
Output: true
Test Case 2:
Input: 121.234.12.12
Output: true
Test Case 3:
Input: 000.12.234.23.23
Output: false
Test Case 4:
Input: I.Am.not.an.ip
Output: false