在替换模式中使用正则表达式

时间:2017-02-27 18:40:53

标签: python regex

我有一个python模式,我想用两种不同的方式替换它。

Pattern: <br><b>[Ss][1-2]:[0-9]*-
1)replace by " "
2)replace s/S by Author

我可以做第一个,因为它是一个简单的替换,但我不知道如何进行第二次替换,因为它取决于输入模式,只需要替换表达式的一部分。

这适用于案例1,我只是用空格替换。

text="<br><b>S1:2- you are wrong. I don't think so. <br><b>S2:2- you are wrong"
newtext=re.sub("(<br><b>[Ss][1-2]:[0-9]*-)\s*", ' ',text)
print(newtext)

我们可以在替换字符串中使用变量表达式吗?

替换文字

<br><b>Author1:2- you are wrong. I don't think so. <br><b>Author2:2- you are wrong

1 个答案:

答案 0 :(得分:4)

您可以使用外观语法:

import re
text="<br><b>S1:2- you are wrong. I don't think so. <br><b>S2:2- you are wrong"
re.sub("(?<=<br><b>)[Ss](?=[1-2]:[0-9]*-\s*)", 'Author',text)
# "<br><b>Author1:2- you are wrong. I don't think so. <br><b>Author2:2- you are wrong"