使用带有反向引用的字符串中的 Python Match 对象 [英] Use Python Match object in string with backreferences

查看:39
本文介绍了使用带有反向引用的字符串中的 Python Match 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 是否有能力使用 Match 对象作为带有反向引用的字符串的输入,例如:

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.

推荐答案

您可以使用 re.sub(而不是 re.match)来搜索和替换字符串.

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

要使用反向引用,最佳做法是使用原始字符串,例如:r"\1",或双转义字符串,例如"\\1":

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

但是,如果您已经有一个匹配对象,可以使用expand()方法:

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

这篇关于使用带有反向引用的字符串中的 Python Match 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆