Sub topic 5
Literal and regex matching
Many .str methods accept a pattern. Depending on the method, that pattern is either plain text or a regular expression. If you assume the wrong one, you get silent wrong answers, such as a . that matches every character, or an error on a pattern like c++. This chapter shows which methods use which interpretation, how to state your choice explicitly, and how to build patterns safely from untrusted text.
It assumes you know basic Python strings and regular expression syntax (character classes, groups, anchors). It also assumes you know the .str accessor and how missing values behave on a string column from earlier chapters.
Two meanings of a pattern
A literal pattern matches the exact characters you wrote. The pattern a.b matches only the three-character text a.b.
A regular expression pattern treats some characters as operators. In a.b, the dot means "any one character", so it also matches axb and a-b.
The same text can therefore select different rows depending on the interpretation. The next example uses a . in both modes.
import pandas as pd
s = pd.Series(["v1.5", "v125", "v1x5", None], dtype="string")
as_regex = s.str.contains(".", regex=True, na=False)
as_literal = s.str.contains(".", regex=False, na=False)
print(as_regex.tolist())
print(as_literal.tolist())The regex version returns [True, True, True, False], because every non-missing string contains some character. The literal version returns [True, False, False, False], because only v1.5 contains a dot. The None entry becomes False in both cases because of na=False.
Which methods use which mode
Defaults differ between methods, and one default changed between pandas versions. The table summarizes the behavior in pandas 2.x.
| Method | How the pattern is read | Notes |
|---|---|---|
| `contains` | Regex by default | Pass `regex=False` for plain text. |
| `replace` | Literal by default | Since pandas 2.0. Earlier versions defaulted to regex. |
| `split`, `rsplit` | Regex if `regex=None` and the pattern is longer than one character | A single character is always literal. |
| `match`, `fullmatch` | Always regex | There is no `regex` argument. |
| `extract`, `extractall`, `findall`, `count` | Always regex | |
| `startswith`, `endswith`, `find` | Always literal | A `^` or `$` here is just a character. |
Do not memorize this table. Pass regex=True or regex=False whenever a method accepts the argument. Your code then stays correct when defaults change, and a reader does not have to remember them.
Replacing text: literal versus regex
replace shows the difference most clearly. The same call produces very different output depending on regex.
import pandas as pd
s = pd.Series(["a.b.c", "x.y"], dtype="string")
print(s.str.replace(".", "-", regex=False).tolist())
print(s.str.replace(".", "-", regex=True).tolist())
print(s.str.replace(r"\.", "-", regex=True).tolist())The first call returns ['a-b-c', 'x-y']. The second returns ['-----', '---'], because every character matched. The third escapes the dot with a backslash, so it behaves like the literal call.
If you only need to swap one piece of fixed text for another, use regex=False. It is easier to read and avoids escaping mistakes.
Groups and callables
Regex mode adds two features that literal mode lacks. First, you can refer to captured groups in the replacement with \1, \2, and so on. Second, you can pass a function as the replacement. It receives a re.Match object and returns the new text.
import pandas as pd
dates = pd.Series(["2024-03-05", "2023-12-31"], dtype="string")
reordered = dates.str.replace(
r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", regex=True
)
print(reordered.tolist())
no_zeros = dates.str.replace(
r"\d+", lambda m: str(int(m.group())), regex=True
)
print(no_zeros.tolist())The first result is ['05/03/2024', '31/12/2023']. The second is ['2024-3-5', '2023-12-31'], because each run of digits is converted to an integer and back to text, which drops leading zeros.
A callable replacement, case=False, and flags all require regex=True. Combining them with regex=False raises a ValueError.
Anchoring: contains, match, and fullmatch
Three methods all test a regex, but they test different amounts of the string.
containssucceeds if the pattern matches anywhere (likere.search).matchsucceeds if the pattern matches at the start (likere.match).fullmatchsucceeds only if the pattern matches the whole string.
import pandas as pd
codes = pd.Series(["AB-12", "xAB-12", "AB-12-extra", None], dtype="string")
pat = r"AB-\d+"
result = pd.DataFrame(
{
"code": codes,
"contains": codes.str.contains(pat),
"match": codes.str.match(pat),
"fullmatch": codes.str.fullmatch(pat),
}
)
print(result)The three columns give these results for the four rows:
AB-12:True,True,True.xAB-12:True,False,False.AB-12-extra:True,True,False.- Missing value:
<NA>in all three columns.
For validation, such as "is every value a well-formed code", prefer fullmatch. People often reach for contains and forget the anchors, so xAB-12 passes as valid.
Case and flags
Regex options can be set in two ways. For case-insensitive matching, the case=False argument is the short form. For anything else, pass a flag from the standard re module.
import re
import pandas as pd
log = pd.Series(["ERROR: disk", "error: net", "info: ok"], dtype="string")
print(log.str.contains("error", case=False).tolist())
print(log.str.contains("^error", flags=re.IGNORECASE).tolist())
print(log.str.contains(r"error|info", flags=re.IGNORECASE).tolist())All three calls are valid. The first returns [True, True, False], and the second returns the same. The third returns [True, True, True].
Building patterns from variable text
If part of a pattern comes from a variable, such as a search box, a config file, or another column, it may contain regex operators. Characters like +, (, [, *, ?, . and $ change the meaning of the pattern. Some, like c++, are invalid and raise an error. Others are valid but match the wrong rows.
You have two safe options.
- Use
regex=Falsewhen the whole pattern is plain text. - Use
re.escapeon the untrusted portion when you need regex features around it, such as alternation or anchors.
import re
import pandas as pd
s = pd.Series(["Learn C++", "learn c", "C++ intro", None], dtype="string")
term = "c++"
pattern = re.escape(term)
print(s.str.contains(pattern, case=False, na=False).tolist())
print(s.str.contains(term, case=False, regex=False, na=False).tolist())Both lines print [True, False, True, False]. Calling s.str.contains("c++") without escaping or regex=False fails, because the regex engine sees a repeat operator applied to another repeat operator.
To match any of several user-supplied terms, escape each one and join them with |.
import re
import pandas as pd
s = pd.Series(["a.b", "axb", "c(d)", "plain"], dtype="string")
terms = ["a.b", "c(d)"]
pattern = "|".join(re.escape(t) for t in terms)
print(s.str.contains(pattern, na=False).tolist())The result is [True, False, True, False]. Without escaping, a.b would also match axb, and c(d) would match the text cd instead of c(d).
Missing values and the na argument
Every matching method returns a missing entry for a missing input. On a string column the result has the nullable boolean dtype, and the entry is <NA>. Using that result directly as a filter mask raises an error, because the mask contains missing values. On an object column the result can fall back to object dtype, which behaves worse.
Set na to choose what a missing value means for your filter.
na=Falsetreats missing text as "does not match". This is the usual choice for selecting rows.na=Truetreats missing text as "matches". Use it when you want to keep rows you cannot judge, such as when excluding rows that match a bad pattern.
import pandas as pd
s = pd.Series(["alpha", None, "gamma"], dtype="string")
keep = s[s.str.contains("a", na=False)]
drop_bad = s[~s.str.contains("gam", na=False)]
print(keep.tolist())
print(drop_bad.tolist())The first list is ['alpha', 'gamma']. The second is ['alpha', <NA>], so the missing row survives the exclusion filter. This is the behavior you want when a missing value is not evidence of a bad one.
Common errors
- Capture-group warning.
containswith a pattern that has capture groups, such as(ab)+, gives aUserWarningsaying the pattern has match groups and suggestingstr.extract. If you only need grouping, use a non-capturing group:(?:ab)+. - Unescaped separators in
split. A multi-characterpatis treated as a regex whenregexis unset. Splitting on"||"therefore does not split on two pipes. Uses.str.split("||", regex=False)instead. - Old code that relied on the
replacedefault. Code written for pandas 1.x that calleds.str.replace(r"\d+", "")withoutregex=Truenow treats the pattern as literal text and changes nothing. Passregex=Trueexplicitly. - Regex syntax differs with the pyarrow backend. Methods on a pyarrow-backed
stringcolumn hand regex work to the Arrow library, which uses the RE2 engine. RE2 does not support lookarounds or backreferences in the pattern. Depending on the pandas version, such a pattern raises an error or falls back to slower Python matching. Keep patterns simple when you rely on that backend.
Summary of the habits
- Pass
regex=explicitly on every method that accepts it. - Use
re.escapefor any pattern text you did not write yourself. - Use
fullmatchfor validation andcontainsfor search. - Use
na=Falseorna=Truedeliberately whenever the result becomes a mask. - Use non-capturing groups
(?:...)when you do not need captures.
Exercise
A string column title contains values such as "Intro to C++", "c++ tips", "Learning C", "Python (basics)", and missing values. Write one expression that selects the rows containing the text (basics) or c++, ignoring case, where the search terms come from a Python list terms. Missing values must not be selected and no error may occur.
Show answer
Escape each term, join with |, and use na=False:
import re
pattern = "|".join(re.escape(t) for t in terms)
df[df["title"].str.contains(pattern, case=False, na=False)]
With terms = ["(basics)", "c++"], re.escape turns the parentheses and plus signs into literal characters, so there is no regex error and (basics) is matched as text instead of a group. na=False removes the missing rows from the mask.
Exercise
Given s = pd.Series(["AB-12", "AB-12-extra", "xAB-12"], dtype="string"), which of contains, match, and fullmatch with the pattern AB-\d+ return True for exactly one row, and which row is it?
Show answer
Only fullmatch returns True for exactly one row, "AB-12". contains returns True for all three rows because the pattern appears somewhere in each. match returns True for "AB-12" and "AB-12-extra", because it anchors only the start of the string.