re is Python’s standard-library module for recognizing, extracting, searching, and replacing text that fits regular-expression patterns. It provides a more flexible alternative to simple substring methods. section 3.2.4 section 16.7
Core ideas include:
- A regular expression is a pattern string whose metacharacters can match many specific strings. section 16.1
- re.compile(pattern) creates a compiled regular expression; compilation is optional but can improve performance when processing large amounts of text. section 16.1
- search(text) returns a match object when the pattern occurs and None when it does not. section 16.1
- sub(replacement, text) replaces matching portions, while other methods support splitting, extraction, position lookup, and controlled iteration. section 16.7
- Prefixing a pattern string with r makes it a raw string, so Python does not process its escape sequences first. section 16.7
Normalize irregular whitespace
import re x = "live and let \t \tlive" pattern = re.compile(r"[\t ]+") pattern.sub(" ", x) # 'live and let live' section 3.2.4
Count matching lines
regexp = re.compile("hello") count = 0 for line in file.readlines(): if regexp.search(line): count += 1 # search detects whether each line contains the pattern section 16.1
x = "live and let \t \tlive"
x.split()
['live', 'and', 'let', 'live']
x.replace(" let \t \tlive", "enjoy life")
'live and enjoy life'
import re #1
regexpr = re.compile(r»[\t ]+»)
regexpr.sub(" ", x)
'live and let live'
#1 re module used to replace all spaces
Compare ordinary splitting and replacement with a compiled regular expression that collapses mixed spaces and tabs. section 3.2.4

