Skip to content
shellhacks.dev
Regular Expressions

Match an IPv4 octet

Match one IPv4 octet, the numbers 0 to 255, with an alternation of three ranges. The check below tries every number to 300 and counts exactly 256 matches.

1 min read
Summarize in AI

A pattern for an IP address needs a piece that accepts 0 to 255 and nothing above, and [0-9]{1,3} accepts 999.

Python
import re

octet = r"(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
rx = re.compile(rf"{octet}")
ok = [n for n in range(0, 300) if rx.fullmatch(str(n))]
print(len(ok), ok[0], ok[-1])
print(bool(rx.fullmatch("007")), bool(rx.fullmatch("256")))

ip = re.compile(rf"{octet}(\.{octet}){{3}}")
for s in ["10.0.0.1", "255.255.255.255", "256.1.1.1", "1.2.3", "01.2.3.4"]:
    print(f"{s:16} {bool(ip.fullmatch(s))}")
Text
256 0 255
False False
10.0.0.1         True
255.255.255.255  True
256.1.1.1        False
1.2.3            False
01.2.3.4         False

The three alternatives cover 250 to 255, 200 to 249 and 100 to 199, and the last one covers 0 to 99 with an optional tens digit. Python's fullmatch anchors the pattern, as in the re documentation. The count of 256 matches among the numbers up to 299 shows that nothing above 255 is accepted, and the second pattern repeats the octet three more times with dots.

Order matters when the pattern is not anchored: with the short form [1-9]?[0-9] first, a search in 255 would find only 25. The pattern rejects leading zeros such as 007, which some tools read as octal. For anything beyond a quick filter use the ipaddress module in Python or inet_pton in C, which handle IPv6 and edge cases.

Share

More snippets

Regular Expressions

Match a quoted string

Match a quoted string with a negated character class. An escaped quote inside the text ends the match early, and a PCRE alternation that pairs backslashes handles it.

1 min read
Regular Expressions

Match a semantic version

Match a semantic version with the pattern from semver.org, which runs in grep -E. It rejects leading zeros, a bare 1.2 and a v prefix, and takes pre-release tags.

1 min read
Regular Expressions

Match a UUID

Match a version 4 UUID with 8-4-4-4-12 hex groups, a 4 at the start of the third group and 8, 9, a or b at the start of the fourth. Add -i for uppercase.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.