Quantcast
Channel: Python - Replace part of regex? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Adam Smith for Python - Replace part of regex?

$
0
0

Two ways to do this, either capture your pre- and post-fixes, or use lookbehinds and lookaheads.

# captures = "Example {String}"replaced = re.sub(r'({).*?(})', r'\1a\2', s)# lookarounds = "Example {String}"replaced = re.sub(r'(?<={).*?(?=})', r'a', s)

If you capture you pre- and post-fixes, you're able to use those capture groups in your substitution using \{capture_num}, e.g. \1 and \2.

If you use lookarounds, you essentially DON'T MATCH those pre-/post-fixes, you simply assert that they are there. Thus the substitution only swaps the letters in between.

Of course for this simple sub, the better solution is probably:

re.sub(r'{.*?}', r'{a}', s)

Viewing all articles
Browse latest Browse all 2

Trending Articles