What are the Java regular expressions for matching IPv4 and IPv6 strings?

Tags: regex java

Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.


The regex allows the use of leading zeros in the IPv4 parts.

Some Unix and Mac distros convert those segments into octals.

I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d as an IPv4 segment.

By : Aeron

Another good option for processing IPs is to use Java's classes Inet4Address and Inet6Address, which can be useful in a number of ways, one of which is to determine the validity of the IP address.

I know this doesn't answer the question directly, but just thought it's worth mentioning.

By : Yuval

Here's a regex to match IPv4 addresses:


You'll need to escape the backslashes when you specify it as a string literal in Java:

By : hasseg

This video can help you solving your question :)
By: admin