pola-rs/polars · error · TypeError
"extract_groups" expects a `str`, given a
Error message
"extract_groups" expects a `str`, given a {qualified_type_name(pattern)!r} What it means
polars' Expr.str.extract_groups() extracts named regex capture groups and requires the pattern to be a Python `str`. If a non-string (e.g. an Expr, bytes, or None) is passed, polars raises a TypeError immediately instead of deferring to the engine, since the pattern cannot be compiled.
Solutions
- Pass a plain Python `str` as the pattern
- Decode bytes with `.decode('utf-8')` if the pattern came from a file or network
- If the pattern must be dynamic, build the string first and pass the resulting str
Example fix
// before
pl.col('url').str.extract_groups(b'(?P<q>.*)')
// after
pl.col('url').str.extract_groups('(?P<q>.*)') Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(pattern, str):
raise TypeError(f'extract_groups pattern must be str, got {type(pattern).__name__}') Type guard
def is_str_pattern(p) -> TypeGuard[str]:
return isinstance(p, str) Try / catch
try:
expr = pl.col('url').str.extract_groups(pattern)
except TypeError:
pattern = str(pattern)
expr = pl.col('url').str.extract_groups(pattern) Prevention
- Annotate pattern parameters as `str` so type checkers catch non-str inputs
- Decode bytes read from files before using as regex patterns
When it happens
Trigger: Calling `df.select(pl.col('url').str.extract_groups(some_expr))` or passing a variable holding a non-str value (e.g. bytes, an Expr, or None) as `pattern`.
Common situations: Reading a regex from config/CLI that was parsed into a non-string type; accidentally passing a pl.col() expression instead of a literal pattern; getting bytes from a file read without decoding.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- arr.to_struct() got a str instead of a list. hint: pass
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
- cannot call `map_groups` when grouping by named expressions
- cannot set Series of dtype
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/b863b73a6b188fae.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/expr/string.py:1736
>>> (
... df.with_columns(
... captures=pl.col("url").str.extract_groups(pattern)
... ).with_columns(name=pl.col("captures").struct["1"].str.to_uppercase())
... )
shape: (3, 3)
┌─────────────────────────────────┬───────────────────────┬──────────┐
│ url ┆ captures ┆ name │
│ --- ┆ --- ┆ --- │
│ str ┆ struct[2] ┆ str │
╞═════════════════════════════════╪═══════════════════════╪══════════╡
│ http://vote.com/ballon_dor?can… ┆ {"messi","python"} ┆ MESSI │
│ http://vote.com/ballon_dor?can… ┆ {"weghorst","polars"} ┆ WEGHORST │
│ http://vote.com/ballon_dor?err… ┆ {null,null} ┆ null │
└─────────────────────────────────┴───────────────────────┴──────────┘
"""
if not isinstance(pattern, str):
msg = f'"extract_groups" expects a `str`, given a {qualified_type_name(pattern)!r}'
raise TypeError(msg)
return wrap_expr(self._pyexpr.str_extract_groups(pattern))
def count_matches(self, pattern: str | Expr, *, literal: bool = False) -> Expr:
r"""
Count all successive non-overlapping regex matches.
.. engine-support:: in-memory, streaming, distributed
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
Returns
-------View on GitHub (pinned to fe841f959e)