Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java regex matching IP Address

A pretty cool exercise in writing Java Regular Expressions is to write Java regex matching IP Address. In this post we’ll show IP regexp and use in IP Address validator.

Regular Expression to match IP Address

The crucial part in IP address validation is matching numbers between 0 and 255. This can be done with the following Regular Expression:

String zeroTo255 = "([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])";

What it means:

  • (): whole group consists of three alternatives separated with | (pipe)
  • [01]?[0-9]{1,2}: (the 1st group) matches any number between 0 and 199,
  • [01]?: 0 or 1 may appear at most once at front of the number,
  • [0-9]{1,2}: digits 0 to 9 may appear exactly once or twice on the 2nd or 3rd position in the number,
  • 2[0-4][0-9]: (the 2nd group) matches numbers between 200 and 249, where the first digit is always 2, the second is between 0 and 4, and the third digit is any between 0 and 9,
  • 25[0-5]: (the 3rd group) matches numbers between 250 and 255, where 25 is always at front and the third digit is between 0 and 5.

With the above regexp it’s easy to create a more complex expression that will match all four parts of IPv4 Address:

String IP_REGEXP = zeroTo255 + "\\." + zeroTo255 + "\\."
                 + zeroTo255 + "\\." + zeroTo255;

Having Java Regex matching IP Address we can write a simple validator.

IP Address Validator class

In this code we are using the Regular Expressions described above, but compile them once into the Java Pattern, because it needs to be compiled only once. Having the Pattern object we can use it to obtain a Match for a given String and try to match ip regexp:


import java.util.regex.Pattern;

public class IpAddressValidator {

    private static final String zeroTo255
            = "([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])";

    private static final String IP_REGEXP
            = zeroTo255 + "\\." + zeroTo255 + "\\."
            + zeroTo255 + "\\." + zeroTo255;

    private static final Pattern IP_PATTERN
            = Pattern.compile(IP_REGEXP);

    // Return true when *address* is IP Address
    private boolean isValid(String address) {
        return IP_PATTERN.matcher(address).matches();

IP Address Validator test

We can test the above IPValidator using the following code:

public static void main(String[] args) {
    IpAddressValidator validator = new IpAddressValidator();

    String[] ips = {

    for (String ip : ips) {
        System.out.printf("%20s: %b%n", ip, validator.isValid(ip));

And here are the results of validation:

 true true true true true false false
           123.45: false
Im.not.IP.address: false


Share with the World!