我知道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
为假,但实际上匹配。
text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
# did match
else:
# did not match
参数也可以是接受RE匹配对象并返回替换内容的函数;如果文本不匹配,则不调用此函数。您可以使用它来执行所需的操作,然后只返回要替换为其的常量字符串。这样可以减少对RE不必要的第二次检查。
“字符串是否包含数字”:
repl