Python 在替换模式中使用正则表达式
我有一个python模式,我想用两种不同的方式替换它Python 在替换模式中使用正则表达式,python,regex,Python,Regex,我有一个python模式,我想用两种不同的方式替换它 Pattern: <br><b>[Ss][1-2]:[0-9]*- 1)replace by " " 2)replace s/S by Author 模式:[Ss][1-2]:[0-9]*- 1) 替换为“” 2) 用作者替换s/s 我可以做第一个,因为它是一个简单的替换,但我不确定如何做第二个替换,因为它取决于输入模式,并且只需要替换表达式的一部分 这适用于案例1,我只是用空格替换 text="<br>
Pattern: <br><b>[Ss][1-2]:[0-9]*-
1)replace by " "
2)replace s/S by Author
模式:
[Ss][1-2]:[0-9]*-
1) 替换为“”
2) 用作者替换s/s
我可以做第一个,因为它是一个简单的替换,但我不确定如何做第二个替换,因为它取决于输入模式,并且只需要替换表达式的一部分
这适用于案例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)
text=“
S1:2-你错了。我不这么认为。
S2:2-你错了”
newtext=re.sub((
[Ss][1-2]:[0-9]*-)\s*,“”,text)
打印(新文本)
在替换字符串中可以有一个变量表达式吗
替换文本
<br><b>Author1:2- you are wrong. I don't think so. <br><b>Author2:2- you are wrong
作者1:2-你错了。我不这么认为<作者2:2-你错了
您可以使用环视语法:
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"
重新导入
text=“
S1:2-你错了。我不这么认为。
S2:2-你错了”
re.sub((?您可以使用环视语法:
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"
重新导入
text=“
S1:2-你错了。我不这么认为。
S2:2-你错了”
re.sub(“(?你能为第二个用例提供一个替换样本吗?你能为第二个用例提供一个替换样本吗