Python Basics: Matching Text with re
Small scripts often need to extract a number, check a label, or tidy spaces. Python’s standard-library re module handles patterns in text.
Use Python 3.12 or newer in Bash on Linux. Each example runs independently using strings in memory. The Python code does not read or change data files.
Extract a field
This invented status line contains a task number after task=.
Save as demo_re_1.py:
import re
line = "INFO task=42 status=ready"
match = re.search(r"task=([0-9]+)", line)
if match is not None:
print("Matched:", match.group(0))
print("Task:", int(match.group(1)))
print("Missing:", re.search(r"owner=([a-z]+)", line))Run it from the directory where you saved it:
python3 demo_re_1.pyOutput:
Matched: task=42
Task: 42
Missing: Nonesearch() finds the first match anywhere; check for None before reading groups. Parentheses capture part of a match. Group zero contains the whole match, and group one contains the digits here. [0-9]+ means one or more ASCII digits.
Check the whole value
For this script, a task label must have exactly three uppercase ASCII letters, a hyphen, and two digits.
Save as demo_re_2.py:
import re
pattern = re.compile(r"[A-Z]{3}-[0-9]{2}")
for value in ["JOB-07", "job-07", "JOB-07-extra", "JOB-07\n"]:
print(repr(value), pattern.fullmatch(value) is not None)Run it from the directory where you saved it:
python3 demo_re_2.pyOutput:
'JOB-07' True
'job-07' False
'JOB-07-extra' False
'JOB-07\n' Falsefullmatch() requires the entire string to fit. match() only checks the beginning. compile() creates a reusable pattern; {3} means exactly three repetitions. This checks the label’s shape, not whether the task exists.
Collapse whitespace
Save as demo_re_3.py:
import re
text = " queue\t ready\n now "
clean = re.sub(r"\s+", " ", text).strip()
print(repr(clean))
print("Original:", repr(text))Run it from the directory where you saved it:
python3 demo_re_3.pyOutput:
'queue ready now'
Original: ' queue\t ready\n now 'sub() returns a new string. Here \s+ includes newlines, so this deliberately flattens lines.
Use raw strings such as r"\s+" for patterns with backslashes. \d also matches non-ASCII decimal digits; choose [0-9] when that matters. For literal input inside a pattern, use re.escape(). Prefer str.replace() for a fixed substring, and a format-specific parser for structured documents.
References
Acknowledgements
This post was created with assistance from AI.