pola-rs/polars · error · TypeError

escape_regex function is unsupported for `Expr`, you may wan

Error message

escape_regex function is unsupported for `Expr`, you may want use `Expr.str.escape_regex` instead

What it means

Top-level pl.escape_regex escapes regex metacharacters of a plain Python string so it can be embedded safely in a pattern. It operates on host strings only; passing an Expr is a common slip when column-wise escaping is wanted, so the error explicitly redirects to Expr.str.escape_regex.

Source

Thrown at py-polars/src/polars/functions/escape_regex.py:24

with contextlib.suppress(ImportError):  # Module not available when building docs
    import polars._plr as plr
import polars._reexport as pl


def escape_regex(s: str) -> str:
    r"""
    Escapes string regex meta characters.

    Parameters
    ----------
    s
        The string whose meta characters will be escaped.

    """
    if isinstance(s, pl.Expr):
        msg = "escape_regex function is unsupported for `Expr`, you may want use `Expr.str.escape_regex` instead"
        raise TypeError(msg)
    elif not isinstance(s, str):
        msg = f"escape_regex function supports only `str` type, got `{qualified_type_name(s)}`"
        raise TypeError(msg)

    return plr.escape_regex(s)

View on GitHub (pinned to df599052da)

Solutions

  1. For column-wise escaping use the expression namespace: pl.col('s').str.escape_regex()
  2. Keep pl.escape_regex for plain str literals you splice into a pattern: pl.col('x').str.contains(pl.escape_regex(user_input) + '.*')

Example fix

# before
pl.escape_regex(pl.col('s'))  # TypeError

# after
pl.col('s').str.escape_regex()
Defensive patterns

Strategy: type-guard

Type guard

def safe_escape_regex(s):
    if isinstance(s, pl.Expr):
        return s.str.escape_regex()  # column-wise
    return pl.escape_regex(s)  # plain string

Prevention

When it happens

Trigger: pl.escape_regex(pl.col('s')); pl.escape_regex(some_expr) inside a select/with_columns pipeline where per-row escaping was intended.

Common situations: Building a contains pattern from user input and mistakenly escaping a column instead of the literal; refactoring from string constants to columns.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/10632f078f8b230e. Report an issue: GitHub.