Regex-based text filtering
Filter or flag records whose text matches a regex, such as alternative words or structured tokens.
Polars · Module
Checks whether each string contains text matching a pattern. Patterns are regular expressions by default, with options for literal matching and invalid-pattern handling.
Call this string namespace method on a Series or expression to produce Boolean results indicating whether each string contains a match. The pattern is a regular expression by default; set literal=True for fixed-text matching, and use strict=False to convert invalid-pattern errors into null results.
Series.str.contains(pattern: str | Expr, *, literal: bool = False, strict: bool = True) → Series| Name | Type | Description |
|---|---|---|
pattern | str | Expr | Regular-expression pattern to search for; may also be an expression. |
literal | bool = False | Interpret pattern as fixed text instead of regex syntax. |
strict | bool = True | Raise on an invalid regex when true; otherwise produce null for the invalid match. |
Series of data type Boolean.
import polars as pl
df = pl.DataFrame({"text": ["Crab", "cat and dog", "rab$bit", None]})
result = df.select(
pl.col("text").str.contains("cat|bit").alias("regex"),
pl.col("text").str.contains("rab$", literal=True).alias("literal"),
)
print(result)Returns Boolean columns for regex matching and literal substring matching.
Filter or flag records whose text matches a regex, such as alternative words or structured tokens.
Search for punctuation or other fixed text that has special meaning in regex syntax.
Apply a case-insensitive search by embedding an inline regex modifier in the pattern.
The method searches each string for a match to pattern and returns a Boolean Series or expression. pattern is regex syntax unless literal=True is supplied.
Follow-up: How would you perform a case-insensitive match? Use an inline regex modifier, for example (?i)AA, in the pattern.
literal=True disables regex interpretation, so characters such as $ are matched as text. The result remains Boolean for non-null inputs and preserves nulls.
Follow-up: What happens for a null input? The corresponding output is null rather than True or False.
strict controls invalid-regex handling. The default strict=True raises an error, while strict=False masks the invalid match with a null value.
Follow-up: Why might strict=False be useful? It allows a pipeline to continue when patterns are external or user-provided, while exposing invalid matches as null.
Expr.str.containsSeries.str.contains_anyExpr.str.starts_withExpr.str.ends_with