regex - Use Python Match object in string with backreferences -
does python have capability use match object input string backreferences, eg:
match = re.match("ab(.*)", "abcd") print re.some_replace_function("match is: \1", match) // prints "match is: cd" you implement using usual string replace functions, i'm sure obvious implementation miss edge cases resulting in subtle bugs.
you can use re.sub (instead of re.match) search , replace strings.
to use back-references, best practices 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 have match object , can use expand() method:
mo = re.match(r"ab(.*)", "abcd") result = mo.expand(r"match is: \1") print(result) # -> match is: cd
Comments
Post a Comment