 <pre><code>re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--') </code></pre> <p>Explanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (as many spaces as there were characters in said substring, in this case).</p>