Javatpoint Logo
Javatpoint Logo

Java IP Address (IPv4) Regex Examples

IP address are the unique numerical identifiers of each devices connected to a network. The first version of the IP addresses is a 32-bit address separated by period (.).

In Java, Regex or Regular Expression is an API that defines the string patterns. It is widely used for searching, validating, and manipulating string and passwords. In this section, we will learn how to validate IP address with regular expression (regex).

IP Address Validation Rules

  • The IP address must be in the form of string like A.B.C.D
  • The length of A, B, C, or D can't be greater than 3.
  • The value of A, B, C, and D should lie between 0 to 255. Following are the valid combinations of each number of an IP address.
    1. Any one- or two-digit number.
    2. Any 3-digit number beginning with 1.
    3. Any 3-digit number beginning with 2 if the second digit is 0 through 4.
    4. Any 3-digit number beginning with 25 if the third digit is 0 through 5.
  • Leading 0's is not allowed.


Input: str = ""

Output: True

Input: str = ""

Output: False

Input: str = ""

Output: False

Regular Expression for IP Address

Get the String.

Create a regular expression to validate an IP address.

// regular expression to validate numbers from 0 to 255

zeroTo255 -> (\\d{1, 2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])

//regular expression to validate complete IP address

IPAddress -> zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255 + "\\." + zeroTo255;

  • \d denotes the regular expression to represent number from o to 9.
  • \\d{1, 2} represents any 1 or 2 digits number.
  • (0|1)\\d{2} represents a three digit number which is starting from 0 or 1.
  • 2[0-4]\\d represents numbers between 200 and 249.
  • 25[0-5] represents number between 250 and 255.

In order to match the pattern Java Pattern class provides the matcher() function. The method creates a patten that matches he given input against this pattern. It returns true if the string matches with the given regex, else return false.


Note: There may be more than one regular expression to validate IP addresses.

Some Other Regular Expression for IP Addresses



Let's create a Java program that validates the IP addresses.


Output: true
Output: true
Output: false
Output: false

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA