Regular expressions for valid IP version 4 and IP version 6 addresses

This uses java.util.regex.Pattern

Regular Expressions are

Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
Pattern IPV6_PATTERN= Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
Pattern IPV6_HEX_COMPRESSED_PATTERN	= Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

Here is a demo

public static void main(String args[])
{
 
 String exampleIP="127.0.0.1";
 System.out.println("Is it a valid IP?:"+IPV4_PATTERN.matcher(exampleIP).matches()); 

}

Let me know if you have any questions.


No responses yet

Leave a Reply