Regex for IPv4 address

Use /^(?:(?: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)$/ to check that a whole string is a valid for IPv4 address. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:(?: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)$/
Open in Regex Tester
InputResult
192.168.1.1✓ Match
8.8.8.8✓ Match
255.255.255.255✓ Match
0.0.0.0✓ Match
256.1.1.1✗ No match
192.168.1✗ No match
01.2.3.4✗ No match
1.2.3.4.5✗ No match
192.168.1.1/24✗ No match

How the pattern works

PartMeaning
25[0-5]250–255
2[0-4]\d200–249
1\d\d100–199
[1-9]?\d0–99, without a leading zero
(?:…\.){3}Three numbers, each followed by a dot
(?:…)$The fourth number, then the end of the string

Code examples

JavaScript

const re = /^(?:(?: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.test(value); // true or false

Python

import re

bool(re.fullmatch(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)', value))

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)$/', $value) === 1;

Notes and limitations

Each octet is checked to be 0–255, which a simple \d{1,3} pattern can’t do. Leading zeros are rejected because some systems read them as octal. To accept CIDR notation, append (?:\/(?:3[0-2]|[12]?\d))? before the $.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for IPv4 address?
/^(?:(?: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)$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 192.168.1.1, 8.8.8.8, 255.255.255.255, 0.0.0.0. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.