Reputation: 3832
I have the following piece of code:
import re
s = "Example {String}"
replaced = re.sub('{.*?}', 'a', s)
print replaced
Which prints:
Example a
Is there a way to modify the regex so that it prints:
Example {a}
That is I would like to replace only the .* part and keep all the surrounding characters. However, I need the surrounding characters to define my regex. Is this possible?
Upvotes: 2
Views: 289
Reputation: 54243
Two ways to do this, either capture your pre- and post-fixes, or use lookbehinds and lookaheads.
# capture
s = "Example {String}"
replaced = re.sub(r'({).*?(})', r'\1a\2', s)
# lookaround
s = "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)
Upvotes: 5