【问题标题】:using a regex in replacement pattern在替换模式中使用正则表达式
【发布时间】:2017-02-28 02:51:31
【问题描述】:

我有一个 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

【问题讨论】:

  • 您能否提供第二个用例的替换示例

标签: python regex


【解决方案1】:

您可以使用环视语法:

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"

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2017-04-30
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多