Java Regular Expressions - Validate IP Addresses
Check if IP Address is Valid Or Not with Java
Regular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.
A common way to use them is to check whether a number is valid - i.e. follows a pattern. IP addresses follow a particular pattern, and can be tested with Regular Expressions.
This can also include validating Subnet masks, country-specific IPs, or any other criteria. In this example, we are just checking if a number is a valid IP or not:
public class RegexTutorial { public static void main(String[] args) { // Looking for a valid IP Address. Pattern pattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); Matcher matcher = pattern.matcher("192.168.1.1"); boolean match = matcher.matches(); System.out.println(match); } } The output will be:
true This is a valid IP Address since this matches our criteria of 4 numbers separated by dots. All numbers are within the range of a valid IP Address too:
public class RegexTutorial { public static void main(String[] args) { // Looking for a valid IP Address. Pattern pattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); Matcher matcher = pattern.matcher("400.168.1.1"); boolean match = matcher.matches(); System.out.println(match); } } The output will be:
false This is invalid since 400 is out of our IP Address range.

