tags:

views:

1811

answers:

5

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

+5  A: 
public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";

Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.

Kevin Wong
Yes, no doubt someone should come up with a single, all encompassing regex -- these are far, far too short as is.
Will Hartung
Thanks! These are a good starting point. But I've found that IPV6_HEXCOMPRESSED_REGEX will accept "1::2:3:4:5:6:7:8", which isn't valid since you can't have more than 8 groupings and :: implies more compressed groupings.
gusterlover6
+1  A: 

Here's a regex to match IPv4 addresses:

\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

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

"\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
hasseg
A: 

You have specified : in the IPv4 pattern, don't you think this is used in IPv6 only?

?: is part of the reg-ex pattern, not the IP it's parsing.
gusterlover6
+2  A: 

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.

Yuval
A: 

The regex allows the use of leading zero's in the IPv4 parts.

Some Unix and Mac distro's convert those segments into octals

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

Aeron