
In our Polars string guide, we covered basic text cleaning. When your data demands pattern-level precision, Polars regex delivers — it builds Regular Expression (Regex) support directly into its .str namespace, so you never leave the DataFrame API.
Polars regex runs every pattern match across your entire DataFrame in parallel. That means no Python loops, no .apply() bottlenecks, and no trade-off between expressiveness and speed. Whether you’re filtering user records, stripping junk characters, or extracting structured values from messy strings, the .str namespace handles it with a single expression.
The Setup
import polars as pl
df = pl.DataFrame({
"id": ["user_1", "user_2", "prod_3", "user_4"],
"code": ["ABC-123-DEF", "XYZ-456-GHI", "ABC-789-JKL", "ERR-000-XXX"]
})1. Polars Regex Filtering with str.contains()
Target every row where id starts with "user". The ^ anchor pins the match to the start of the string.
df.filter(
pl.col("id").str.contains(r"^user")
)str.contains() accepts any valid regex pattern and evaluates it across every row without leaving the lazy or eager execution graph.
2. Polars Regex Cleaning with str.replace_all()
Strip every hyphen from the code column in a single expression.
df.with_columns(
pl.col("code").str.replace_all("-", "").alias("code_no_hyphens")
)Output:
... │ ABC123DEF │ │ XYZ456GHI │ ...
Unlike str.replace(), which stops at the first match, str.replace_all() applies the pattern to every occurrence in the string. Use it anytime your cleaning rule is pattern-based, not positional.
3. Polars Regex Extraction with str.extract()
str.extract() is the most surgical tool in the Polars regex toolkit. Use a capture group (\d{3}) to pull the three-digit segment out of each code string.
# Group 0 = full match (e.g., "ABC-123-DEF")
# Group 1 = first capture group (the digits)
df.with_columns(
pl.col("code").str.extract(r"(\d{3})", 1).alias("middle_numbers")
)Output:
... │ 123 │ │ 456 │ │ 789 │ │ 000 │ ...
Capture groups let you target exactly the part of the string you need. Group 0 returns the full match. Group 1 returns the first parenthesised pattern. Add more groups for more complex extractions.
Polars executes this across all rows in parallel — a pattern that scales where Python loops cannot.
Key Takeaways
- Polars regex delivers first-class Regular Expression support through the
.strnamespace — no external libraries required. - Use
str.contains()to filter rows by pattern, such as matching rows whereidstarts with'user'. - Use
str.replace_all()to clean data at scale — remove hyphens, special characters, or any pattern-matched noise across every row. - Use
str.extract()with capture groups to isolate structured values from messy strings. - All Polars regex operations run in parallel across the full DataFrame, making them significantly faster than row-by-row Python approaches.





