我知道 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
为false,但实际上是匹配的。
最佳答案
使用re.subn
Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).
然后检查替换的次数。例如:
text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
# did match
else:
# did not match
关于Python:如何替换并知道是否匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3969519/