Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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

like image 261
Kevin Wong Avatar asked Sep 05 '08 16:09

Kevin Wong


People also ask

What would be the regex to validate the IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

What is regex pattern matching?

A regular expression is a pattern of text that consists of ordinary characters, for example, letters a through z, and special characters. Matches pattern anywhere in the name.


1 Answers

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.

like image 135
Kevin Wong Avatar answered Nov 22 '22 10:11

Kevin Wong