Sub topic 5
Literal and regex matching
This chapter assumes you can write basic Python regular expressions and that you know the .str accessor from the previous chapter. The examples use a string dtype column, but the rules are the same for object columns.
Why the choice matters
Some .str methods read the pattern you give them as a regular expression (regex), and others read it as plain text. The defaults differ between methods. A pattern such as "." or "a+b" can match the wrong rows, and pandas raises no error when it does.
A literal pattern and a regex pattern differ
str.contains treats its pattern as a regex by default. A dot matches any character.
import pandas as pd
s = pd.Series(["a.b", "axb", "A.B"], dtype="string")
print(s.str.contains("."))
print(s.str.contains(".", regex=False))The first call returns True for every row, because each value has at least one character. The second call returns True, False, True, because only "a.b" and "A.B" contain a real dot. Pass regex=False whenever you mean "this exact text".
str.replace has the opposite default. Since pandas 2.0 it treats the pattern as literal text unless you pass regex=True.
import pandas as pd
s = pd.Series(["a.b", "axb", "A.B"], dtype="string")
print(s.str.replace(".", "-"))
print(s.str.replace(".", "-", regex=True))The first call gives a-b, axb, A-B. The second replaces every character, so each value becomes ---. Older tutorials may assume the old default, so check your pandas version when code behaves differently.
Which methods use regex
| Method | Pattern is read as |
|---|---|
| `str.contains` | Regex by default. Use `regex=False` for literal text. |
| `str.replace` | Literal by default. Use `regex=True` for a regex. |
| `str.startswith`, `str.endswith` | Literal text only. |
| `str.removeprefix`, `str.removesuffix` | Literal text only. |
| `str.find` | Literal text only. |
| `str.match`, `str.fullmatch` | Always regex. They anchor the match at the start of the value. |
| `str.extract`, `str.count` | Always regex. |
Escaping text that goes into a regex
You sometimes need a regex for the structure and literal text for part of it. Characters such as +, ., ( and * have special meaning in a regex. re.escape adds backslashes so they are read as plain characters.
import re
import pandas as pd
s = pd.Series(["a+b", "aab", "ab"], dtype="string")
term = "a+b"
print(s.str.contains(term, na=False))
print(s.str.contains(re.escape(term), na=False))
pattern = "^" + re.escape(term)
print(s.str.contains(pattern, na=False))The unescaped pattern means "one or more a, then b". It matches "aab" and "ab" but not "a+b", which is the opposite of what you wanted. The escaped pattern matches only "a+b". The last call shows the usual reason to escape: building a larger regex, here with a ^ anchor, around text that you did not write yourself.
Case and flags
str.contains accepts case=False for case-insensitive matching. For other regex options, pass flags from the re module.
import re
import pandas as pd
s = pd.Series(["Error: disk", "ERROR: net", "ok", None], dtype="string")
print(s.str.contains("error", case=False, na=False))
print(s.str.contains(r"^error", flags=re.IGNORECASE, na=False))Both calls return True, True, False, False. The na=False argument turns the missing entry into False, so the result can be used directly as a filter mask.
Common errors
- Searching for a value that contains
.,(,),[,$or+with the defaultcontains. Addregex=False. - Expecting
str.matchto find text in the middle of a value. It only matches from the start. Usestr.containsto search anywhere. - Passing
flagstogether withregex=False. Flags only apply to regexes, and pandas raises an error. - Skipping
na=Falsebefore using a nullable boolean result as a filter.
Exercise
A column code holds values such as "A(1)", "B(2)" and "A(1)-x", and may contain missing values. Write the expression that selects rows containing the exact text "A(1)", and say why regex=False is used.
Show answer
df[df["code"].str.contains("A(1)", regex=False, na=False)]. Without regex=False, the parentheses form a capture group and the pattern means "A1", which does not match "A(1)". With regex=False, the text is compared as is. na=False makes missing values False so the mask can filter rows.