In this program, we will check a given IP address is valid or not using the matches() method by applying regular expression.
Program/Source Code:
The source code to check a given IP address is valid or not is given below. The given program is compiled and executed successfully.
// Java program to check a given IP address
// is valid or not
public class Main {
public static boolean validate(final String ip) {
String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";
return ip.matches(PATTERN);
}
public static void main(String[] args) {
String ip1 = "192.168.10.5";
String ip2 = "192.1681.10.5";
if (validate(ip1) == true)
System.out.println("IP address is valid");
else
System.out.println("IP address is not valid");
if (validate(ip2) == true)
System.out.println("IP address is valid");
else
System.out.println("IP address is not valid");
}
}
Output:
IP address is valid
IP address is not valid
Explanation:
In the above program, we created a public class Main. It contain two static methods validate() and main().
The validate() method returns true when the given string contains a valid IP address otherwise it returns false.
The main() method is an entry point for the program. Here, we used the regular expression in matches() method to check a given IP address is valid or not and printed the appropriate message.
In this program, we will check a given IP address is valid or not using the matches() method by applying regular expression.
Program/Source Code:
The source code to check a given IP address is valid or not is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a public class Main. It contain two static methods validate() and main().
The validate() method returns true when the given string contains a valid IP address otherwise it returns false.
The main() method is an entry point for the program. Here, we used the regular expression in matches() method to check a given IP address is valid or not and printed the appropriate message.