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.
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
reas written.re.ASCIIkeeps\dto0-9, as in JavaScript (Python matches any Unicode digit otherwise). Usere.fullmatchto 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 theDmodifier,$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.ECMAScriptkeeps\dto0-9, as in JavaScript.$also matches before a final newline; to reject one, end the pattern with\zinstead.
Common mistakes
Leading zeros are rejected on purpose
Some parsers, including
inet_atonin C, read010as octal 8. Rejecting01.2.3.4keeps two programs from disagreeing about the address.Valid is not public
10.0.0.1,192.168.1.1,127.0.0.1and0.0.0.0all pass. Check the range separately before connecting to an address a user gave you.Use a strict address parser
Python
ipaddress.ip_addressand Gonetip.ParseAddrreject shorthand and leading zeros and give you a typed address. .NETIPAddress.TryParseaccepts1.2and reads010as octal, so keep the pattern in front of it.