Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java regex matching IP Address

farenda 2017-03-20 0

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:

package com.farenda.java.util.regex;

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 = {
            "1.2.3.4",
            "000.12.23.034",
            "121.234.9.1",
            "23.45.56.12",
            "255.255.255.255",
            "255.1.0.256",
            "00.11.22.33.44",
            "123.45",
            "Im.not.IP.address"
    };

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

And here are the results of validation:

          1.2.3.4: true
    000.12.23.034: true
      121.234.9.1: true
      23.45.56.12: true
  255.255.255.255: true
      255.1.0.256: false
   00.11.22.33.44: false
           123.45: false
Im.not.IP.address: false

References:

  • Check out Java Tutorials if you want to learn more!
Share with the World!
Categories Java Tags java, java-util, regex
Previous: Static Factory Method pattern
Next: Java regex remove duplicated words

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok