Regex replace (in Python) - a simpler way?


Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:


And then concatenate the start group with the new data for replace and then the end group.

Is there a better method for this?

4/17/2013 10:23:24 PM

Accepted Answer

Look in the Python re documentation for lookaheads (?=...) and lookbehinds (?<=...) -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.

1/29/2009 5:51:21 AM

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" %, s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow