PYTHON · PYTHON FOR EVERYONE · CHAPTER 13

Regular expressions

Find IPs in a log, validate MAC addresses and turn the output of a show command into data with the re module.

10 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you know how to search for fixed text with in or str.find(), but you don't know how to find "any IP address" or "any MAC" inside a log. Point B: by the end of this chapter, you'll write patterns with regular expressions and use the re module to extract IPs from a syslog, validate MAC addresses and turn the output of show ip interface brief into structured data.

What a regular expression is

A regular expression (regex) is a pattern that describes a set of strings. With it, you don't ask "does 10.0.0.1 appear?" but "does something shaped like an IP address appear?".

You've already used something similar in the terminal: ls *.cfg lists everything that ends in .cfg. That shell wildcard isn't a regex, but the idea is the same: one pattern that stands for many strings. Regexes are far more expressive.

In Python, you work with them through the standard library's re module. Its syntax is similar to Perl's, so what you learn here carries over to many other tools.

Write patterns as raw strings

Regexes use the backslash a lot: \d, \., \b. But in a regular Python string, the backslash already has its own meaning: \n is a newline and \b a backspace.

The solution is to write the pattern as a raw string, with the r prefix. In r"10\.0", the backslash reaches the re module intact. If you forget the r, Python warns you:

pattern = "10\.0"
print(pattern)
$ python3 pattern.py
/home/ana/pattern.py:1: SyntaxWarning: "\." is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\."? A raw string is also an option.
  pattern = "10\.0"
10\.0

The path in the warning is your file's. The program works, but the warning tells you that this code will stop being valid.

Python 3.14 update. The book wrote patterns as regular strings, for example "...\.". It worked because Python 2 let unknown escape sequences through. In Python 3.12 and later, that produces a SyntaxWarning, and the documentation says it will stop working. Always use r"..." for your patterns.

Literals, wildcard, alternatives and classes

The simplest regex is literal text: "R1" only matches R1. From there, you add metacharacters, symbols with a special meaning:

  • . matches any character except a newline. Exactly one.
  • | expresses an alternative: Gi|Fa|Te.
  • ( ) forms a group: (Gi|Fa|Te)0/1 limits the alternative to the part that changes.
  • [ ] forms a class: a single character from those listed. A dash defines ranges ([0-9], [a-f]), and a ^ at the start negates it ([^0-9]).
  • \ escapes a metacharacter so you can use it as a literal: \. is an actual dot.
import re

print(re.match("R1", "R1"))                         # → <re.Match object; span=(0, 2), match='R1'>
print(re.match(".1", "R1"))                         # → <re.Match object; span=(0, 2), match='R1'>
print(re.match(".1", "SW1"))                        # → None
print(re.match("10.0", "1000"))                     # → <re.Match object; span=(0, 4), match='1000'>
print(re.match(r"10\.0", "1000"))                   # → None
print(re.match("Gi|Fa|Te", "Te0/1"))                # → <re.Match object; span=(0, 2), match='Te'>
print(re.match("(Gi|Fa|Te)0/1", "Fa0/1"))           # → <re.Match object; span=(0, 5), match='Fa0/1'>
print(re.match("Vlan[0-9]", "Vlan7"))               # → <re.Match object; span=(0, 5), match='Vlan7'>
print(re.match("[0-9a-fA-F][0-9a-fA-F]", "3C"))     # → <re.Match object; span=(0, 2), match='3C'>
print(re.match("Gi0/1[.:]", "Gi0/1.100"))           # → <re.Match object; span=(0, 6), match='Gi0/1.'>
print(re.match("Vlan[^0-9]", "VlanX"))              # → <re.Match object; span=(0, 5), match='VlanX'>

Look at the fourth line: "10.0" matches 1000 because the dot accepts any character. It's the most common mistake when searching for IP addresses. The fifth line fixes it by escaping the dot.

Inside a class, almost all metacharacters lose their meaning. That's why [.:] looks for a literal dot or colon. Escaping them there ([\.:]) changes nothing in Python, but you don't need to either.

Special sequences

Some classes are used so often that they have a shortcut:

SequenceMatchesOpposite
\dA digit\D: anything that isn't a digit
\wA word character: letter, digit or underscore\W
\sA whitespace character: space, tab, newline…\S
\bA word boundary (doesn't consume characters)\B
import re

print(re.findall(r"\d", "Gi0/1"))              # → ['0', '1']
print(re.findall(r"\w+", "R1 sw_core-02"))     # → ['R1', 'sw_core', '02']
print(re.findall(r"\S+", "R1   up\tup"))       # → ['R1', 'up', 'up']
print(re.match(r"\d", "٣"))                    # → <re.Match object; span=(0, 1), match='٣'>
print(re.match(r"\d", "٣", re.ASCII))          # → None
Python 3.14 update. The book said that \d is equivalent to [0-9] and \w to [a-zA-Z0-9_]. In Python 3, strings are Unicode, and those sequences also accept accented letters or digits from other scripts, like the Arabic ٣ in the example. If you need exactly the ASCII characters, for example when validating an IP, add the re.ASCII flag or write the explicit class [0-9].

Repetitions

Writing \d\d\d\d for 4 digits doesn't scale. Quantifiers say how many times whatever is on their left can appear, whether it's a character, a class or a group:

QuantifierMeaning
+1 or more times
*0 or more times
?0 or 1 time (optional)
{3}Exactly 3 times
{1,3}Between 1 and 3 times
{,2}Between 0 and 2 times
{3,}3 or more times
import re

text = "Vlan Vlan1 Vlan20 Vlan300 Vlan4094"
print(re.findall(r"Vlan\d+", text))          # → ['Vlan1', 'Vlan20', 'Vlan300', 'Vlan4094']
print(re.findall(r"Vlan\d*", text))          # → ['Vlan', 'Vlan1', 'Vlan20', 'Vlan300', 'Vlan4094']
print(re.findall(r"Vlans?", "Vlan Vlans"))   # → ['Vlan', 'Vlans']
print(re.findall(r"Vlan\d{3}\b", text))      # → ['Vlan300']
print(re.findall(r"Vlan\d{1,2}\b", text))    # → ['Vlan1', 'Vlan20']
print(re.findall(r"Vlan\d{,2}\b", text))     # → ['Vlan', 'Vlan1', 'Vlan20']
print(re.findall(r"Vlan\d{3,}", text))       # → ['Vlan300', 'Vlan4094']

Quantifiers are greedy: they grab as much as they can. If you add a ? after them (+?, *?), they become lazy and grab as little as possible:

import re

line = "203.0.113.45(51234) -> 192.0.2.10(22)"
print(re.search(r"\((.+)\)", line).group(1))    # → 51234) -> 192.0.2.10(22
print(re.search(r"\((.+?)\)", line).group(1))   # → 51234

Anchors: start, end and word boundaries

Sometimes where the pattern appears matters. ^ requires it to be at the start of the string, and $, at the end. \b marks the edge of a word, which helps you avoid confusing up with UPDOWN or setup.

import re

print(re.search(r"^%LINK", "%LINK-3-UPDOWN: Interface Gi0/1"))   # → <re.Match object; span=(0, 5), match='%LINK'>
print(re.search(r"^%LINK", "R1 %LINK-3-UPDOWN"))                 # → None
print(re.search(r"down$", "changed state to down"))              # → <re.Match object; span=(17, 21), match='down'>
print(re.search(r"\bup\b", "changed state to up"))               # → <re.Match object; span=(17, 19), match='up'>
print(re.search(r"\bup\b", "UPDOWN setup"))                      # → None

Named groups

Remembering that the severity is group 2 is fragile: if you add a group before it, all the numbers change. With (?P<name>...), you give each group a name and look it up by that name. groupdict() returns a dictionary ready to use.

import re

line = "Oct 24 10:01:12 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down"
pattern = r"%(?P<facility>\w+)-(?P<severity>\d)-(?P<mnemonic>\w+)"

m = re.search(pattern, line)
print(m.group("facility"))    # → LINK
print(m["severity"])          # → 3
print(m.groupdict())          # → {'facility': 'LINK', 'severity': '3', 'mnemonic': 'UPDOWN'}

If you need parentheses only to group, without capturing, use (?:...). You'll see it in the IP pattern in the next section.

findall and finditer: every match

re.findall() returns a list with all the matches. If the pattern has capturing groups, the list holds the groups instead of the full text; that's why you should use (?:...) when you don't need them. re.finditer() returns an iterator of Match objects, one per match, which is useful when you want positions or named groups.

First networking case: extracting the IP addresses from a syslog.

import ipaddress
import re

log = """\
Oct 24 10:02:40 R1 %OSPF-5-ADJCHG: Nbr 10.0.0.2 on Gi0/0 from FULL to DOWN
Oct 24 10:05:13 R1 %SEC-6-IPACCESSLOGP: list 101 denied tcp 203.0.113.45(51234) -> 192.0.2.10(22)
Oct 24 10:06:01 R1 %BGP-5-ADJCHANGE: neighbor 198.51.100.7 Up
Oct 24 10:07:30 R1 %SYS-4-WEIRD: peer 300.1.2.999 rejected
"""

IP = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
candidates = re.findall(IP, log)
print(candidates)

for text in candidates:
    try:
        ipaddress.ip_address(text)
    except ValueError:
        print(f"{text} isn't a valid IPv4 address")

for m in re.finditer(IP, log):
    print(m.group(), "at position", m.start())
    break
['10.0.0.2', '203.0.113.45', '192.0.2.10', '198.51.100.7', '300.1.2.999']
300.1.2.999 isn't a valid IPv4 address
10.0.0.2 at position 39

The pattern looks for 4 blocks of 1 to 3 digits separated by dots. It recognizes the shape of an IP, but it doesn't check that each octet is at most 255. For that, the right tool is the ipaddress module: let the regex find candidates and let ipaddress decide.

sub and split: replacing and splitting

re.sub(pattern, repl, string) replaces each match. With count=, you limit how many. re.subn() does the same and also tells you how many replacements it made. In the replacement, you can reuse a group with \1, \2…

re.split(pattern, string) cuts the string at each match. With maxsplit=, you limit the number of cuts. It's more flexible than str.split() because the separator can vary.

import re

IP = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
line = "denied tcp 203.0.113.45(51234) -> 192.0.2.10(22)"
print(re.sub(IP, "x.x.x.x", line))
print(re.sub(IP, "x.x.x.x", line, count=1))
print(re.subn(IP, "x.x.x.x", line))

print(re.sub(r"\bGi(\d)", r"GigabitEthernet\1", "Gi0/1 and Gi0/2"))

print(re.split(r"[,;\s]+", "R1, R2;R3   R4"))
print(re.split(r"[,;\s]+", "R1, R2;R3   R4", maxsplit=2))
denied tcp x.x.x.x(51234) -> x.x.x.x(22)
denied tcp x.x.x.x(51234) -> 192.0.2.10(22)
('denied tcp x.x.x.x(51234) -> x.x.x.x(22)', 2)
GigabitEthernet0/1 and GigabitEthernet0/2
['R1', 'R2', 'R3', 'R4']
['R1', 'R2', 'R3   R4']

The first use is very practical: anonymizing the IPs in a log before you share it in a ticket or a forum.

Fact. Always pass count, maxsplit and flags by keyword. Since Python 3.13, passing them by position, as in re.sub(p, r, s, 1), raises a DeprecationWarning.

compile and flags

The module's functions build a Pattern object internally every time you call them. re.compile() gives you that object to reuse: it has the same methods (match, search, findall, sub…), without repeating the pattern.

Python keeps a cache of recently used patterns, so the performance gain is usually small. The main reason to compile is a different one: giving the pattern a name and defining it only once.

Flags change the behavior. You combine them with |:

  • re.IGNORECASE (re.I): ignores the difference between uppercase and lowercase.
  • re.VERBOSE (re.X): ignores whitespace and allows # comments inside the pattern.
  • re.MULTILINE (re.M): ^ and $ work on each line, not just at the start and end of the text.
  • re.ASCII (re.A): \d, \w and friends only accept ASCII.
import re

severity = re.compile(r"%\w+-(?P<level>[0-7])-", re.IGNORECASE)
print(type(severity))     # → <class 're.Pattern'>

events = [
    "%LINK-3-UPDOWN: Interface Gi0/1, changed state to down",
    "%SYS-5-CONFIG_I: Configured from console",
    "%link-3-updown: interface gi0/2, changed state to down",
]
critical = [e for e in events if int(severity.search(e)["level"]) <= 3]
print(len(critical))      # → 2

In syslog, the lower the severity, the more serious the event: 0 is emergency and 7, debugging. This filter keeps what goes from 0 to 3.

Use case: validating a MAC address

A MAC has 6 bytes in hexadecimal, but it's written in several ways: with colons, with dashes or in groups of 4 separated by dots, as on Cisco devices. With re.VERBOSE, you can write each format on its own line and comment it:

import re

MAC = re.compile(r"""
      (?:[0-9a-f]{2}:){5}[0-9a-f]{2}     # 00:1a:2b:3c:4d:5e
    | (?:[0-9a-f]{2}-){5}[0-9a-f]{2}     # 00-1A-2B-3C-4D-5E
    | (?:[0-9a-f]{4}\.){2}[0-9a-f]{4}    # 001a.2b3c.4d5e (Cisco style)
""", re.IGNORECASE | re.VERBOSE)

tests = ["00:1a:2b:3c:4d:5e", "00-1A-2B-3C-4D-5E", "001a.2b3c.4d5e",
         "00:1a:2b:3c:4d", "00:1a:2b:3c:4d:5g", "00:1a-2b:3c:4d:5e"]
for text in tests:
    status = "valid" if MAC.fullmatch(text) else "invalid"
    print(f"{text:<20}{status}")
00:1a:2b:3c:4d:5e   valid
00-1A-2B-3C-4D-5E   valid
001a.2b3c.4d5e      valid
00:1a:2b:3c:4d      invalid
00:1a:2b:3c:4d:5g   invalid
00:1a-2b:3c:4d:5e   invalid

3 decisions make it work. fullmatch() rejects text with extra characters. re.IGNORECASE accepts uppercase or lowercase hexadecimal. And each alternative fixes a single separator, so the last test, which mixes : and -, is rejected.

Use case: parsing show ip interface brief

Many devices return text meant for people. Before you automate, you need to turn it into data. This is the typical pattern: a regex with named groups, re.MULTILINE to anchor each row and finditer() to go through them.

import re

output = """\
Interface              IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0     10.0.0.1        YES manual up                    up
GigabitEthernet0/1     unassigned      YES unset  administratively down down
GigabitEthernet0/2     192.168.10.1    YES DHCP   up                    down
Loopback0              1.1.1.1         YES manual up                    up
"""

ROW = re.compile(r"""
    ^(?P<interface>\S+) \s+
    (?P<ip>\S+)         \s+
    (?:YES|NO)          \s+
    (?P<method>\S+)     \s+
    (?P<status>up|down|administratively\ down) \s+
    (?P<protocol>up|down) \s*$
""", re.VERBOSE | re.MULTILINE)

for m in ROW.finditer(output):
    row = m.groupdict()
    if row["status"] == "up" and row["protocol"] == "down":
        print(f"Check {row['interface']}: status up, protocol down")
    print(row)
{'interface': 'GigabitEthernet0/0', 'ip': '10.0.0.1', 'method': 'manual', 'status': 'up', 'protocol': 'up'}
{'interface': 'GigabitEthernet0/1', 'ip': 'unassigned', 'method': 'unset', 'status': 'administratively down', 'protocol': 'down'}
Check GigabitEthernet0/2: status up, protocol down
{'interface': 'GigabitEthernet0/2', 'ip': '192.168.10.1', 'method': 'DHCP', 'status': 'up', 'protocol': 'down'}
{'interface': 'Loopback0', 'ip': '1.1.1.1', 'method': 'manual', 'status': 'up', 'protocol': 'up'}

The header row doesn't fit (it has neither YES nor NO) and gets dropped on its own. In VERBOSE mode, whitespace is ignored, which is why the space in administratively down is escaped: \ .

This approach takes practice and breaks easily if the format changes. When the device offers an API that returns JSON, as you'll see in chapter 15, that's a better option than parsing text.

Challenge

Answer before you open the solution.

1. Why can re.search("192.168.1.1", text) find 192x168y1z1?

Because an unescaped dot is a wildcard. Write it as r"192\.168\.1\.1", or use re.escape() to escape literal text.

2. You want to check that a text is a VLAN number and nothing else. match, search or fullmatch?

fullmatch. match would accept 20abc because it only looks at the start, and search would accept abc20.

3. What does re.findall(r"(\d+)\.(\d+)", "10.20 30.40") return?

[('10', '20'), ('30', '40')]. With several capturing groups, findall returns tuples with the groups, not the full text.

4. Your \d{1,3} pattern accepts 999 as an octet. Do you make it more complex or switch tools?

Switch tools. Use the regex to find candidates and ipaddress.ip_address() to validate. The code ends up clearer and correct.

5. What does re.MULTILINE do to ^ and $?

It makes them work on each line. Without the flag, ^ only matches at the start of the whole text and $ at the end.

Key takeaways

  • A regex describes a set of strings; always write it as a raw string r"...".
  • ., |, ( ), [ ], quantifiers and anchors are the basic building blocks. Escape the dot in IPs.
  • In Python 3, \d and \w accept Unicode; use re.ASCII if you need ASCII only.
  • match looks at the start, search at any position and fullmatch at the whole string.
  • Named groups and groupdict() turn text into dictionaries.
  • findall, finditer, sub and split cover searching, replacing and splitting; pass count and maxsplit by keyword.
  • Combine regexes with specialized modules like ipaddress instead of forcing impossible patterns.

In the next chapter, you go down a level: you'll open TCP and UDP connections with sockets and build your own client and server.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate