Skip to content

Commit bfb930c

Browse files
committed
ENH: str.replace accepts a compiled expression
.str.replace now accepts a compiled regular expression. See pandas-dev#15446
1 parent be4a63f commit bfb930c

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

pandas/core/strings.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -377,22 +377,29 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
377377
# Check whether repl is valid (GH 13438, GH 15055)
378378
if not (is_string_like(repl) or callable(repl)):
379379
raise TypeError("repl must be a string or callable")
380-
use_re = not case or len(pat) > 1 or flags or callable(repl)
380+
is_re = isinstance(pat, re._pattern_type)
381+
build_re = not is_re and (not case or len(pat) > 1 or flags or callable(repl))
381382

382-
if use_re:
383+
if is_re:
384+
f = _str_replace_regex_func(pat, repl, n)
385+
elif build_re:
383386
if not case:
384387
flags |= re.IGNORECASE
385388
regex = re.compile(pat, flags=flags)
386-
n = n if n >= 0 else 0
387-
388-
def f(x):
389-
return regex.sub(repl, x, count=n)
389+
f = _str_replace_regex_func(regex, repl, n)
390390
else:
391391
f = lambda x: x.replace(pat, repl, n)
392392

393393
return _na_map(f, arr)
394394

395395

396+
def _str_replace_regex_func(regex, repl, n=-1):
397+
n = n if n >= 0 else 0
398+
def f(x):
399+
return regex.sub(repl, x, count=n)
400+
return f
401+
402+
396403
def str_repeat(arr, repeats):
397404
"""
398405
Duplicate each string in the Series/Index by indicated number

0 commit comments

Comments
 (0)