Regex for IPv4 addresses

A regular expression for dotted-decimal IPv4 addresses that checks each number is between 0 and 255, a version for pulling addresses out of log files, and the parsers that disagree about leading zeros.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

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

An IPv4 address in its usual form is four numbers from 0 to 255 separated by dots. A pattern such as ^\d{1,3}(\.\d{1,3}){3}$ is shorter but accepts 999.999.999.999; this one checks the range of each number and refuses leading zeros, which is the strict form most software expects.

The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.

How it works, token by token

PartMeaning
^(?:Start of the string, then a group for the first three parts.
(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])One number from 0 to 255, spelled out as four cases: 250 to 255, 200 to 249, 100 to 199, and 0 to 99 (an optional first digit 1 to 9, then any digit). Because a one- or two-digit number cannot start with 0, leading zeros are rejected.
\.A literal dot. Unescaped, . would match any character.
){3}The number-and-dot group exactly three times.
(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])The fourth number, with no dot after it.
$End of the string.

What it matches and what it rejects

InputResultWhy
0.0.0.0matchesThe lowest value.
127.0.0.1matchesLoopback.
192.168.1.1matchesA private address.
255.255.255.255matchesThe highest value.
203.0.113.9matchesAn address reserved for documentation.
256.1.1.1rejected256 is out of range.
192.168.1rejectedOnly three parts.
192.168.1.1.1rejectedFive parts.
192.168.01.1rejectedA leading zero.
192.168.1.1/24rejectedA CIDR prefix is not part of an address.
1.2.3.-4rejectedNo signs.
␣192.168.1.1rejectedA leading space.

Why leading zeros are rejected

Older software, including the C library's inet_aton, reads a part with a leading zero as octal and accepts shortened forms such as 127.1. Browsers still do this when parsing a URL, following the WHATWG URL Standard:

console.log(new URL('http://192.168.1.010/').hostname);  // → 192.168.1.8   010 is read as octal
console.log(new URL('http://0x7f.1/').hostname);         // → 127.0.0.1
print(socket.inet_ntoa(socket.inet_aton('127.1')))  # → 127.0.0.1   the old C parser fills in the gap

So 192.168.1.010 can mean .10 to one program and .8 to another. That ambiguity has led to security bugs where an allow-list and the code that connects disagree about the address. Python's ipaddress module stopped accepting leading zeros in version 3.9.5 for this reason (see the ipaddress documentation), and the pattern on this page does the same.

Finding addresses in logs

To pull addresses out of a log line, replace ^ and $ with \b, a word boundary, so that the match cannot start or end in the middle of a longer number:

/\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\b/

Searching this text:

Blocked 203.0.113.9 and 198.51.100.300; version 1.2.3.4.5

finds 2 matches:

1. 203.0.113.9
2. 1.2.3.4

The out-of-range 198.51.100.300 is skipped rather than cut down to a shorter address, but a version number with five parts still yields its first four. If that matters, check the characters around each match.

Use the address parser for anything else

Once you know a string is an address, the questions that follow (is it private, is it in this subnet, is it loopback?) are better answered by a parser than a longer pattern. Python has ipaddress, Node.js has net.isIPv4, and .NET has IPAddress.TryParse, though .NET's parser also accepts the older shortened forms, so check with the pattern first if you need the strict form:

ip = ipaddress.ip_address('192.168.1.10')
print(ip.version, ip.is_private)                   # → 4 True
print(ipaddress.ip_address('8.8.8.8').is_global)   # → True
try:
    ipaddress.ip_address('192.168.01.10')
except ValueError:
    print('rejected')                              # → rejected
console.log(isIPv4('192.168.1.10'), isIPv4('256.1.1.1'));  // → true false

The examples on this page use 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24, the ranges RFC 5737 sets aside for documentation. To work with ranges and masks, try the subnet calculator.

In JavaScript, Python, PHP and C#

JavaScript

const re = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/;
console.log(re.test('0.0.0.0')); // → true
console.log(re.test('256.1.1.1')); // → false

Python

import re

pattern = re.compile(r'(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])')
print(bool(pattern.fullmatch('0.0.0.0')))  # → True
print(bool(pattern.fullmatch('256.1.1.1')))  # → False

PHP

<?php
$pattern = '/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/D';
echo preg_match($pattern, '0.0.0.0'), "\n"; // → 1
echo preg_match($pattern, '256.1.1.1'), "\n"; // → 0

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\z");
Console.WriteLine(pattern.IsMatch("0.0.0.0")); // → True
Console.WriteLine(pattern.IsMatch("256.1.1.1")); // → False

Each version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

What is the regex for an IP address?

For IPv4: ^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$. It accepts four numbers from 0 to 255 without leading zeros. IPv6 needs a separate pattern.

Should 192.168.01.1 be a valid IP address?

It is safer to reject it. Some parsers read 01 as decimal and others as octal, so the same text can mean different addresses. Python's ipaddress module has rejected leading zeros since version 3.9.5.

How do I match an IP address with a CIDR prefix such as /24?

Add (?:\/(?:3[0-2]|[12]?[0-9]))? before the $ to allow a prefix from /0 to /32.