2

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?

1
  • 2
    re.sub('{.*?}', '{a}', s) ? or re.sub('({).*?(})', '\1a\2', s) Commented Feb 9, 2015 at 18:57

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.