1

Does Python have a capability to use a Match object as input to a string with backreferences, eg:

match = re.match("ab(.*)", "abcd")
print re.some_replace_function("match is: \1", match) // prints "match is: cd"

You could implement yourself using usual string replace functions, but I'm sure the obvious implementation will miss edge cases resulting in subtle bugs.

1
  • Was there anything in the documentation? Commented Sep 12, 2017 at 3:49

1 Answer 1

3

You can use re.sub (instead of re.match) to search and replace strings.

To use back-references, the best practices is to use raw strings, e.g.: r"\1", or double-escaped string, e.g. "\\1":

import re

result = re.sub(r"ab(.*)", r"match is: \1", "abcd")
print(result)
# -> match is: cd

But, if you already have a Match Object , you can use the expand() method:

mo = re.match(r"ab(.*)", "abcd")
result = mo.expand(r"match is: \1")
print(result)
# -> match is: cd
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.