{"record":{"id":"b863b73a6b188fae","repo":"pola-rs/polars","slug":"extract-groups-expects-a-str-given-a-qualifi","errorCode":null,"errorMessage":"\"extract_groups\" expects a `str`, given a {qualified_type_name(pattern)!r}","messagePattern":"\"extract_groups\" expects a `str`, given a (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/expr/string.py","lineNumber":1736,"sourceCode":"        >>> (\n        ...     df.with_columns(\n        ...         captures=pl.col(\"url\").str.extract_groups(pattern)\n        ...     ).with_columns(name=pl.col(\"captures\").struct[\"1\"].str.to_uppercase())\n        ... )\n        shape: (3, 3)\n        ┌─────────────────────────────────┬───────────────────────┬──────────┐\n        │ url                             ┆ captures              ┆ name     │\n        │ ---                             ┆ ---                   ┆ ---      │\n        │ str                             ┆ struct[2]             ┆ str      │\n        ╞═════════════════════════════════╪═══════════════════════╪══════════╡\n        │ http://vote.com/ballon_dor?can… ┆ {\"messi\",\"python\"}    ┆ MESSI    │\n        │ http://vote.com/ballon_dor?can… ┆ {\"weghorst\",\"polars\"} ┆ WEGHORST │\n        │ http://vote.com/ballon_dor?err… ┆ {null,null}           ┆ null     │\n        └─────────────────────────────────┴───────────────────────┴──────────┘\n        \"\"\"\n        if not isinstance(pattern, str):\n            msg = f'\"extract_groups\" expects a `str`, given a {qualified_type_name(pattern)!r}'\n            raise TypeError(msg)\n        return wrap_expr(self._pyexpr.str_extract_groups(pattern))\n\n    def count_matches(self, pattern: str | Expr, *, literal: bool = False) -> Expr:\n        r\"\"\"\n        Count all successive non-overlapping regex matches.\n\n        .. engine-support:: in-memory, streaming, distributed\n\n        Parameters\n        ----------\n        pattern\n            A valid regular expression pattern, compatible with the `regex crate\n            <https://docs.rs/regex/latest/regex/>`_.\n        literal\n            Treat `pattern` as a literal string, not as a regular expression.\n\n        Returns\n        -------","sourceCodeStart":1718,"sourceCodeEnd":1754,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/expr/string.py#L1718-L1754","documentation":"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.","triggerScenarios":"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`.","commonSituations":"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.","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"],"exampleFix":"// before\npl.col('url').str.extract_groups(b'(?P<q>.*)')\n// after\npl.col('url').str.extract_groups('(?P<q>.*)')","handlingStrategy":"type-guard","validationCode":"if not isinstance(pattern, str):\n    raise TypeError(f'extract_groups pattern must be str, got {type(pattern).__name__}')","typeGuard":"def is_str_pattern(p) -> TypeGuard[str]:\n    return isinstance(p, str)","tryCatchPattern":"try:\n    expr = pl.col('url').str.extract_groups(pattern)\nexcept TypeError:\n    pattern = str(pattern)\n    expr = pl.col('url').str.extract_groups(pattern)","preventionTips":["Annotate pattern parameters as `str` so type checkers catch non-str inputs","Decode bytes read from files before using as regex patterns"],"tags":["polars","type-error","regex","python"],"backgroundTag":"invalid-argument-value","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}