Sub topic 14
When string methods are not enough
This chapter assumes you know the str methods from the earlier chapters (in, find, replace, split, strip, join). It also assumes you can read a short function and a for loop. You don't need prior regular expression experience. This chapter shows where the plain methods stop working and gives you the first few re tools to go further.
Where plain methods stop
Every method you have used so far matches literal text. replace("cat", "dog") looks for the exact characters c, a, t, in that order, wherever they appear. That is often what you want. It becomes a problem when the thing you are looking for is a pattern rather than a fixed piece of text.
text = "The cat sat on the concatenated catalog."
print("cat" in text)
print(text.replace("cat", "dog"))The output is:
True
The dog sat on the condogenated dogalog.The method has no idea that cat inside concatenated is not the word cat. The same limit shows up in several forms:
- Word boundaries. You want whole words, not substrings.
- Variable content. You want "any run of digits" or "a date", not one specific string.
- Several separators at once.
splittakes one separator, not "a comma or a semicolon or whitespace". - Position rules. You want "digits only at the end of the line".
The re module in the standard library handles these cases. It lets you describe the shape of the text instead of spelling it out.
A short tour of the pattern language
A regular expression (regex) is a pattern string that describes a set of strings. These pieces cover most everyday use:
| Piece | Meaning | Column |
|---|---|---|
| `\d` | one digit | |
| `\w` | one letter, digit, or underscore | |
| `\s` | one whitespace character | |
| `.` | any character except a newline | |
| `\b` | a word boundary (an edge between `\w` and a non-`\w` character) | |
| `[,;]` | any one character from the set | |
| `+` | one or more of the previous item | |
| `*` | zero or more of the previous item | |
| `{4}` | exactly four of the previous item | |
| `^`, `$` | start and end of the string | |
| `a\ | b` | `a` or `b` |
Patterns are written as raw strings (r"..."). In a normal string literal, Python processes backslashes before re sees them, and that breaks patterns:
print(len("\b")) # 1, a single backspace character
print(len(r"\b")) # 2, a backslash and the letter bIf you write "\bcat\b" without the r, the pattern contains backspace characters and silently matches nothing useful. Get in the habit of writing r"..." for every pattern.
The functions that mirror string methods
Each common re function replaces a string method you already know. The names are close enough to remember.
| String method | `re` counterpart | What changes |
|---|---|---|
| `in`, `find` | `re.search` | Returns a match object or `None`, not a position |
| `startswith` | `re.match` | Anchored at the start only |
| `==` on the whole string | `re.fullmatch` | The entire string must fit the pattern |
| `replace` | `re.sub` | The target is a pattern, and the replacement can be a function |
| `split` | `re.split` | The separator is a pattern |
| `count` | `len(re.findall(...))` | Counts pattern matches |
Whole words with `\b`
import re
text = "The cat sat on the concatenated catalog."
print(re.sub(r"\bcat\b", "dog", text))The output is The dog sat on the concatenated catalog. Only the standalone word changed.
Splitting on several separators
import re
line = "apples, oranges;bananas grapes"
print(re.split(r"[,;\s]+", line))The output is ['apples', 'oranges', 'bananas', 'grapes']. The + collapses runs such as , into one separator. A chain of replace calls followed by split() could do the same job, but the pattern states the intent in one line.
Pulling out variable content
import re
log = "order 17 shipped 3 items on 2026-11-26"
print(re.findall(r"\d+", log))The output is ['17', '3', '2026', '11', '26']. No combination of find calls can say "any run of digits" without a manual loop.
Replacing with a function
re.sub accepts a function as the replacement. The function receives a match object and returns the new text.
import re
def double(match):
return str(int(match.group()) * 2)
print(re.sub(r"\d+", double, "3 apples and 10 pears"))The output is 6 apples and 20 pears.
Named groups
Parentheses capture part of a match. Naming the groups makes the code self-documenting.
import re
m = re.search(r"(?P<key>\w+)\s*=\s*(?P<value>.+)", "timeout = 30")
if m:
print(m.group("key"), m.group("value"))The output is timeout 30. When no match is found, re.search returns None. Always test the result before calling .group(), or you will get an AttributeError.
Case-insensitive matching
For literal text, you learned to compare with casefold(). In a pattern, pass a flag:
import re
print(re.findall(r"python", "Python PYTHON python", re.IGNORECASE))The output is ['Python', 'PYTHON', 'python']. Be aware that re.IGNORECASE does simple case matching. It is not the same as casefold(), so do not assume it equates ß with ss. If you need that behavior for a plain comparison, a.casefold() == b.casefold() is still the right tool.
Gotchas
Special characters in your own text
If the text you search for comes from a variable, it may contain characters that have a meaning in patterns, such as ., +, (, or ?. Use re.escape to turn the text back into a literal.
import re
price = "1.5"
text = "values: 1.5, 125, 1x5"
print(re.findall(price, text))
print(re.findall(re.escape(price), text))The first call prints ['1.5', '125', '1x5'] because . matches any character. The second prints ['1.5'].
Greedy matching
Quantifiers such as + and * take as much text as they can. Add ? to make them take as little as possible.
import re
print(re.findall(r"<.+>", "<a><b>"))
print(re.findall(r"<.+?>", "<a><b>"))The first prints ['<a><b>'], one long match. The second prints ['<a>', '<b>'].
Matching the shape is not validating the value
re.fullmatch checks that the whole string fits a pattern. That is a format check only.
import re
def looks_like_date(s):
return re.fullmatch(r"\d{4}-\d{2}-\d{2}", s) is not None
print(looks_like_date("2026-11-26")) # True
print(looks_like_date("2026-11-26x")) # False
print(looks_like_date("2026-99-99")) # True, though no such date existsFor real validation, parse the value with datetime. Also note that \d matches digits from other scripts, not just 0-9. Pass re.ASCII if you need only ASCII digits.
Match versus search
re.match only tries at the start of the string, which surprises people who expect it to behave like in. Use re.search to look anywhere. Use re.fullmatch when the whole string must conform.
When to stay with plain methods
Regex is not an upgrade to use everywhere. A pattern is harder to read than a method name, and it is easier to get subtly wrong. Plain methods are also clearer and often faster for fixed text.
- Use
in,startswith,endswith,replace,partition, andsplit(",")when the text you want is a fixed literal. - Use
removeprefixandremovesuffixfor exact pieces, sincestripand patterns can both remove more than you intended. - Use
translatefor character-by-character mapping. - Reach for
rewhen the target is a shape: variable length, alternatives, boundaries, or position rules. - Do not use regex to parse nested or recursive formats such as HTML, JSON, or source code. Use a real parser (
html.parser,json,ast). - If a pattern grows past a line and you cannot explain it in one sentence, consider splitting the work into several string-method steps or writing a small parser.
Compiling patterns you reuse
If you apply the same pattern many times, for example in a loop over thousands of lines, compile it once. A compiled pattern has the same methods as the module functions.
import re
word_cat = re.compile(r"\bcat\b", re.IGNORECASE)
lines = ["A Cat naps.", "Concatenate this.", "cat, dog"]
for line in lines:
print(bool(word_cat.search(line)))The output is True, False, True, one per line. Compiling also gives the pattern a name, which helps readability.
Putting it together
The earlier cleanup pipeline used split() and join to normalize spaces. When the cleanup needs patterns, the same structure carries over, with re.sub taking the place of replace:
import re
raw = " Call 555-1234 or 555 9876!! "
cleaned = re.sub(r"[^\w\s-]", "", raw).strip()
cleaned = re.sub(r"\s+", " ", cleaned)
print(cleaned)The output is Call 555-1234 or 555 9876. The first sub removes every character that is not a word character, whitespace, or hyphen. The second collapses whitespace runs. Each step is a short, named transformation, which is the same discipline as chaining string methods.
Exercise
Why does "The cat sat".replace("cat", "dog") work, but "concatenate".replace("cat", "dog") give a surprising result? Write a single call that replaces only the standalone word cat in any sentence.
Show answer
replace matches literal characters with no sense of word edges, so it also changes cat inside concatenate, giving condogenate. Use a word boundary pattern: re.sub(r"\bcat\b", "dog", sentence). The r prefix is required so that \b reaches re as a boundary marker instead of a backspace character.
Exercise
A user types a search term into your program, and you build a pattern from it with re.findall(term, text). What goes wrong if the term is a+b, and how do you fix it?
Show answer
In a pattern, + means "one or more of the previous item", so a+b matches ab, aab, and so on, but not the literal text a+b. Escape the term first: re.findall(re.escape(term), text). Better still, when the term is a plain literal and you need no boundaries or other pattern features, term in text or text.count(term) needs no regex at all.
Exercise
You need to pull the values out of a string like "<b>bold</b> and <i>italic</i>". Why does re.findall(r"<.+>", s) return one long match, and what small change returns the individual tags? Should you use regex to parse full HTML pages?
Show answer
The + quantifier is greedy, so .+ consumes as much as possible and runs to the last > in the string. Making it lazy with re.findall(r"<.+?>", s) returns ['<b>', '</b>', '<i>', '</i>']. For full HTML pages you should not use regex, because HTML nests and has many irregular forms. Use html.parser or a dedicated parsing library.