Python:如何替换并知道其是否匹配

问题描述 投票:9回答:3

我知道re.sub(pattern, repl,text)可以在模式匹配时替换,然后返回替换我的代码是

text = re.sub(pattern, repl, text1)

我必须定义另一个变量来检查它是否被修改

text2 = re.sub(pattern, repl, text1)
matches = text2 != text1
text1 = text2

并且它有问题,例如text1='abc123def'pattern = '(123|456)'repl = '123'替换后相同,因此matches为假,但实际上匹配。

python regex
3个回答
16
投票

使用re.subn

执行与sub()相同的操作,但返回一个元组(new_string,number_of_subs_made)。

,然后检查已进行的更换次数。例如:

re.subn

1
投票

text2, numReplacements = re.subn(pattern, repl, text1) if numReplacements: # did match else: # did not match 参数也可以是接受RE匹配对象并返回替换内容的函数;如果文本不匹配,则不调用此函数。您可以使用它来执行所需的操作,然后只返回要替换为其的常量字符串。这样可以减少对RE不必要的第二次检查。


0
投票

“字符串是否包含数字”:

repl
© www.soinside.com 2019 - 2024. All rights reserved.