Developer Toolbox

Regex: IPv4 address

An IPv4 address is four numbers from 0 to 255 joined by dots. \d{1,3} alone would let 999.1.1.1 through, so each number is spelled out as ranges: 250 to 255, 200 to 249, 100 to 199, and 0 to 99 without a leading zero.

Open in Regex Tester The pattern and every example below are filled in.

Pattern

^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$

How it works

^
Start of the string.
((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}
A number and a dot, three times. The number is 25[0-5] (250 to 255), 2[0-4]\d (200 to 249), 1\d\d (100 to 199) or [1-9]?\d (0 to 99).
(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)
The fourth number, the same ranges, with no dot after it.
$
End of the string.

Matches

  • 192.168.1.1
  • 10.0.0.255
  • 0.0.0.0
  • 255.255.255.255

Doesn't match

  • 256.1.1.1
  • 192.168.1
  • 01.2.3.4
  • 1.2.3.4.5

In your language

JavaScript
/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/

A literal; new RegExp(source, flags) builds the same from a string.

Python
re.compile(r"^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$", re.ASCII)

A raw string, so backslashes reach re as written. re.ASCII keeps \d to 0-9, as in JavaScript (Python matches any Unicode digit otherwise). Use re.fullmatch to test a whole string.

Java
Pattern.compile("^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$")

A normal string literal, so every backslash is doubled. matcher(s).matches() tests the whole string.

Go
regexp.MustCompile(`^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$`)

A raw string in backticks. RE2 runs in linear time but has no lookaround and no backreferences.

PHP
preg_match('/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/D', $input)

PCRE with / delimiters inside a single-quoted string. Without the D modifier, $ also matches before a final newline, so it is added to patterns that end in $.

C#
new Regex(@"^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$", RegexOptions.ECMAScript)

A verbatim string: backslashes stay, a quote is doubled. RegexOptions.ECMAScript keeps \d to 0-9, as in JavaScript. $ also matches before a final newline; to reject one, end the pattern with \z instead.

Common mistakes

  • Leading zeros are rejected on purpose

    Some parsers, including inet_aton in C, read 010 as octal 8. Rejecting 01.2.3.4 keeps two programs from disagreeing about the address.

  • Valid is not public

    10.0.0.1, 192.168.1.1, 127.0.0.1 and 0.0.0.0 all pass. Check the range separately before connecting to an address a user gave you.

  • Use a strict address parser

    Python ipaddress.ip_address and Go netip.ParseAddr reject shorthand and leading zeros and give you a typed address. .NET IPAddress.TryParse accepts 1.2 and reads 010 as octal, so keep the pattern in front of it.