Course contentsShow
← Java
Lesson 2287 of 2,87044. Regular ExpressionsFree lesson

IP Address Patterns (IPv4 and IPv6)

Create patterns for IPv4 dotted notation and IPv6 hexadecimal format with optional compression.

IP Address Patterns (IPv4 and IPv6)

You'll learn how to create regular expressions to validate both IPv4 dotted-decimal and IPv6 hexadecimal address formats.

The Core Idea

An IP address uniquely identifies a device on a network. IPv4 uses four decimal numbers (0-255) separated by dots, like 192.168.1.1. IPv6 uses eight groups of four hexadecimal digits separated by colons, like 2001:0db8:85a3:0000:0000:8a2e:0370:7334, with optional zero-compression (::).

Think of these patterns as postal codes for the internet — each format has strict rules about what characters and structures are valid.

IPv4 Pattern

IPv4 requires matching four octets (0-255). A simple pattern:

String ipv4Pattern = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
Pattern pattern = Pattern.compile(ipv4Pattern);
Matcher matcher = pattern.matcher("192.168.0.1");
boolean isMatch = matcher.matches(); // true

More precise (enforcing 0-255 range):

String octet = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)";
String ipv4Precise = octet + "\\." + octet + "\\." + octet + "\\." + octet;

IPv6 Pattern

IPv6 is more complex due to hexadecimal groups and optional compression:

String hexGroup = "[0-9a-fA-F]{1,4}";
String ipv6Full = hexGroup + "(:" + hexGroup + "){7}";
Pattern ipv6Pattern = Pattern.compile(ipv6Full);

Supporting :: compression (zero groups omitted) requires alternation to handle various positions where compression can occur — the full pattern becomes quite elaborate, typically combining multiple alternatives with the pipe operator.

Practical Validation

Pattern ipv4 = Pattern.compile("((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)");
boolean valid = ipv4.matcher("10.0.0.255").matches(); // true

Key Takeaway: IPv4 patterns match four dot-separated octets (0-255), while IPv6 patterns match colon-separated hexadecimal groups with optional zero-compression, requiring careful alternation logic for all valid formats.