regex
Regular expressions for IP v4 and IP v6 addresses
In this example we shall show you how to check if an address is an IPv4 or IPv6 address, using regular expressions. To check an address with regular expressions we have created three different patterns, as described in the steps below:
- The first pattern is creating by compiling a String regular expression that describes the IPv4 address, using
compile(String regex)
API method of Pattern. - The second pattern is creating by compiling a String regular expression that describes the IPv6 standard address, using
compile(String regex)
API method of Pattern. - The third pattern is creating by compiling a String regular expression that describes the IPv6 hex compressed address, using
compile(String regex)
API method of Pattern. - For all three patterns a method is created, that reads the String input address, and using each one of the three patterns creates the Matcher for the pattern, with
matcher(CharSequence input)
API method of Pattern, and checks if the Matcher matches the String input against the pattern, usingmatches()
API method of Matcher,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.regex.Pattern; /** * A collection of utilities relating to InetAddresses. */ public class InetAddressUtils { public static void main(String[] args){ String addr="192.168.1.2"; System.out.println(isIPv4Address(addr)); } private InetAddressUtils() { } private static final 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}$"); private static final Pattern IPV6_STD_PATTERN = Pattern.compile( "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); private static final 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})*)?)$"); public static boolean isIPv4Address(final String input) { return IPV4_PATTERN.matcher(input).matches(); } public static boolean isIPv6StdAddress(final String input) { return IPV6_STD_PATTERN.matcher(input).matches(); } public static boolean isIPv6HexCompressedAddress(final String input) { return IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches(); } public static boolean isIPv6Address(final String input) { return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input); } }
Output:
true
This was an example of how to check if an address is an IPv4 or IPv6 address, using regular expressions in Java.