Validate IP Address
This program validates IPv4 address using regex.
Problem Statement
Write a Java program to validate "192.168.1.1".
Source Code
| 1 | public class RegexIPValidation { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Regex IP Validation"); |
| 4 | String ip="192.168.1.1"; |
| 5 | String regex="^(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\." |
| 6 | +"(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\." |
| 7 | +"(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\." |
| 8 | +"(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"; |
| 9 | if(ip.matches(regex)) System.out.println("Valid IP"); |
| 10 | else System.out.println("Invalid IP"); |
| 11 | } |
| 12 | } |
Program Output
Eduinq Regex IP Validation Valid IP
Explanation
The regex validates each of the four dot-separated octets against the valid 0-255 range using alternation, and matches() checks the whole IP address string against this pattern, demonstrating IPv4 validation.