简体   繁体   中英

Use Python Match object in string with backreferences

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.

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, eg: r"\\1" , or double-escaped string, eg "\\\\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM