{"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":1750,"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":1732,"sourceCodeEnd":1768,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/expr/string.py#L1732-L1768","documentation":"Expr.str.extract_groups returns a struct whose field names come from the named capture groups of the pattern, so the regex must be a literal Python str known at plan-build time. Passing an Expr, Series, bytes, or None raises this TypeError before execution. Column-driven patterns belong to the other extractors in the same namespace.","triggerScenarios":".str.extract_groups(pl.col('pattern')) or passing a Series of patterns; pattern stored as bytes; pattern=None from optional config; mixing this method up with extract/extract_many which do accept pattern columns.","commonSituations":"Patterns loaded from a config table or another column; serialized bytes patterns; refactoring code between extract_groups (literal regex, struct output) and extract_many (per-row pattern lists).","solutions":["Pass the regex as a plain string with named groups: .str.extract_groups(r'(?P<year>\\d{4})-(?P<month>\\d{2})')","If patterns live in a column, use .str.extract_many(pl.col('patterns')) or map_batches with Python re","Decode bytes patterns to str before calling"],"exampleFix":"# before\npl.col('url').str.extract_groups(pl.col('pattern_col'))\n\n# after (literal pattern)\npl.col('url').str.extract_groups(r'(?P<host>[^/]+)/(?P<path>.*)')\n\n# after (per-row patterns)\npl.col('url').str.extract_many(pl.col('pattern_col'))","handlingStrategy":"type-guard","validationCode":"if not isinstance(pattern, str):\n    pattern = str(pattern)  # or raise your own error\nexpr = pl.col('url').str.extract_groups(pattern)","typeGuard":"def is_literal_pattern(x: object) -> bool:\n    return isinstance(x, str)","tryCatchPattern":null,"preventionTips":["Keep regex patterns as module-level str constants","Use extract_many for per-row patterns from a column","Decode bytes patterns at ingestion time","Type-annotate pattern parameters as str so checkers catch misuse"],"tags":["polars","regex","typeerror","string","struct"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}