用Python中的另一个正则表达式模式替换字符串中的正则表达式模式



有没有办法用另一个正则表达式模式替换字符串中的正则表达式模式?我试过了,但没有按预期工作:

s = 'This is a test. There are two tests'
re.sub(r'btest(s)??b', "<b><font color='blue'>btest(s)??b</font></b>", s)

输出为:

"This is a <b><font color='blue'>x08test(s)??x08</font></b>. There are two <b><font color='blue'>x08test(s)??x08</font></b>"

与用html标签封装关键字testtests所需的结果不同:

"This is a <b><font color='blue'>test</font></b>. There are two <b><font color='blue'>tests</font></b>"

如果有解决方法,我如何将其应用于数据帧中的文本列?

提前谢谢。

如果在结果中您想放入它在原始文本中找到的元素,那么您必须将regex放入()(以捕获它(,然后使用1将此元素放入结果中。

re.sub(r'(btest(s)??b)', r"<b><font color='blue'>1</font></b>", s)

BTW:还需要在结果中加前缀r,才能将视为正常字符。

结果:

"This is a <b><font color='blue'>test</font></b>. There are two <b><font color='blue'>tests</font></b>"

如果您将使用更多的(),则每个()都将捕获分离的元素,并且每个元素都将有自己的编号12等。

例如

re.sub(r'(.*) (.*)', r'2 1', 'first second')

给出:

'second first'

在示例中,它也捕获(s),并且具有编号2

您可以使用函数进行替换。

import re

def replacer(match):
return f"<b><font color='blue'>{match[0]}</font></b>"

s = 'This is a test. There are two tests'
ss = re.sub(r'btest(s)??b', replacer, s)
print(ss)
This is a <b><font color='blue'>test</font></b>. There are two <b><font color='blue'>tests</font></b>

最新更新