Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

Chapter 4Name in the course: Pattern matching with regular expressions

Find and extract text with regular expressions

The re module finds patterns in text: IP addresses in logs, versions in output, settings in config files. The patterns are the same as in grep -E (see regex in RH134), with a few Python extras: named groups and compiled patterns.

  • 4 Lessons
  • 0 Commands

$ run as a normal user# run as root (or with sudo)

4.2

Find all matches

re.findall returns every match; re.finditer gives match objects one by one (good for big texts).

findall.py
import re
from collections import Counter
 
text = open("/var/log/secure", encoding="utf-8", errors="replace").read()
ips = re.findall(r"Failed password for \S+ from (\S+)", text)
for ip, count in Counter(ips).most_common(5):
    print(f"{count:5} {ip}")

4.3

Use named groups

Name the parts of a pattern — the code becomes readable.

named.py
import re
 
pattern = re.compile(
    r"(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] \"(?P<method>\w+) (?P<path>\S+) [^\"]+\" (?P<status>\d{3}) (?P<size>\d+|-)"
)
line = '203.0.113.9 - - [27/Oct/2026:12:01:02 +0300] "GET /admin HTTP/1.1" 403 199'
m = pattern.match(line)
if m:
    d = m.groupdict()
    print(d["ip"], d["path"], d["status"])

4.4

Replace and split

re.sub replaces with a pattern — for example to hide data before you share a log.

sub.py
import re
 
log = "user=anna ip=10.0.0.5 token=abc123def"
masked = re.sub(r"token=\S+", "token=***", log)
anon = re.sub(r"\b\d{1,3}(\.\d{1,3}){3}\b", "x.x.x.x", masked)
print(anon)
print(re.split(r"[,;\s]+", "web1, web2;db1  cache1"))
FlagMeaning
re.IGNORECASE (re.I)Ignore big/small letters
re.MULTILINE (re.M)^ and $ match at every line
re.VERBOSE (re.X)Allow spaces and comments in the pattern