{"record":{"id":"319db337ada2d300","repo":"pandas-dev/pandas","slug":"replace-is-not-supported-with-a-re-pattern-callab","errorCode":null,"errorMessage":"replace is not supported with a re.Pattern, callable repl, case=False, flags!=0, or when the replacement string contains named group references (\\g<...>)","messagePattern":"replace is not supported with a re\\.Pattern, callable repl, case=False, flags!=0, or when the replacement string contains named group references \\(\\\\g<\\.\\.\\.>\\)","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/_arrow_string_mixins.py","lineNumber":262,"sourceCode":"        )\n\n    def _str_replace(\n        self,\n        pat: str | re.Pattern,\n        repl: str | Callable,\n        n: int = -1,\n        case: bool = True,\n        flags: int = 0,\n        regex: bool = True,\n    ) -> Self:\n        if (\n            isinstance(pat, re.Pattern)\n            or callable(repl)\n            or not case\n            or flags\n            or (isinstance(repl, str) and r\"\\g<\" in repl)\n        ):\n            raise NotImplementedError(\n                \"replace is not supported with a re.Pattern, callable repl, \"\n                \"case=False, flags!=0, or when the replacement string contains \"\n                \"named group references (\\\\g<...>)\"\n            )\n\n        if pat == \"\":\n            # pyarrow hangs for empty patterns\n            # (https://github.com/apache/arrow/issues/39149)\n            # use same func definition as ObjectStringArrayMixin._str_replace\n            if regex:\n                count = n if n >= 0 else 0\n                func = lambda val: re.sub(pat, repl, val, count=count)\n            else:\n                func = lambda val: val.replace(pat, repl, n)\n\n            result = self._apply_elementwise(func)\n            return self._from_pyarrow_array(\n                pa.chunked_array(result, type=self._pa_array.type)","sourceCodeStart":244,"sourceCodeEnd":280,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/_arrow_string_mixins.py#L244-L280","documentation":"NotImplementedError raised in _str_replace of the ArrowStringArray mixin when the call uses features the pyarrow backend cannot express: a compiled re.Pattern as pat, a callable repl, case=False, non-zero flags, or a replacement string containing named group references (\\g<...>). pandas surfaces this so users know to fall back rather than get silently wrong output.","triggerScenarios":"On a pyarrow-backed string Series: s.str.replace(re.compile(r'\\d+'), 'x'); s.str.replace('a', lambda m: m.group(0).upper()); s.str.replace('a','b', flags=re.I); s.str.replace('a','\\g<name>').","commonSituations":"Enabling the pyarrow string dtype globally (pd.options.future.infer_string or dtype=str[pyarrow]) and then using advanced regex replace patterns previously written for object strings.","solutions":["Cast to object dtype for that operation: s.astype(object).str.replace(re.compile(r'\\d+'), 'x').","Replace case=False / flags with a regex pattern that embeds the case behavior (e.g. inline (?i)).","Avoid named-group references in repl; use numbered groups (\\1, \\2) which pyarrow supports.","Inline the callable repl as a non-regex transform applied via .map after replace."],"exampleFix":"# before (pa_series is dtype str[pyarrow])\npa_series.str.replace(re.compile(r'\\d+'), 'x')\n# after\npa_series.astype(object).str.replace(re.compile(r'\\d+'), 'x')","handlingStrategy":"fallback","validationCode":"import re\ndef safe_str_replace(s, pat, repl, **kw):\n    unsupported = (\n        isinstance(pat, re.Pattern)\n        or callable(repl)\n        or not kw.get('case', True)\n        or kw.get('flags', 0)\n        or (isinstance(repl, str) and r'\\g<' in repl)\n    )\n    if unsupported and 'pyarrow' in str(s.dtype):\n        s = s.astype(object)\n    return s.str.replace(pat, repl, **kw)","typeGuard":"def needs_object_for_replace(s, pat, repl, case=True, flags=0) -> bool:\n    import re\n    return 'pyarrow' in str(s.dtype) and (\n        isinstance(pat, re.Pattern) or callable(repl)\n        or not case or flags\n        or (isinstance(repl, str) and r'\\g<' in repl)\n    )","tryCatchPattern":"try:\n    s.str.replace(pat, repl, **kw)\nexcept NotImplementedError as e:\n    if 'replace is not supported' in str(e):\n        s.astype(object).str.replace(pat, repl, **kw)\n    else:\n        raise","preventionTips":["On pyarrow-backed strings, prefer plain string patterns with no flags and numbered group references.","Cast to object dtype for the rare replace that needs re.Pattern / callable repl / flags."],"tags":["strings","pyarrow","str-replace","regex"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}