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

gui*_* 桂林 9 python regex

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

text = re.sub(pattern, repl, text1)
Run Code Online (Sandbox Code Playgroud)

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

text2 = re.sub(pattern, repl, text1)
matches = text2 != text1
text1 = text2
Run Code Online (Sandbox Code Playgroud)

并且,它有问题,例如text1='abc123def',pattern = '(123|456)',repl = '123',更换后,这是相同的,所以matches是假的,但实际上它会匹配.

And*_*Dog 16

使用 re.subn

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

然后检查所做的替换次数.例如:

text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
    # did match
else:
    # did not match
Run Code Online (Sandbox Code Playgroud)