Python:如何替换并判断是否匹配
我知道 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),但实际上是匹配的。
3 个回答
0
"判断字符串中是否包含数字":
for text1 in ('abc123def', 'adsafasdfafdsafqw', 'fsadfoi81we'):
print("Text %s %s numbers." %
((text1, ) + (
('does not contain',) if not any(c.isdigit() for c in text1)
else ('contains',))
))
1
repl
参数也可以是一个函数,这个函数会接收一个正则表达式匹配对象,并返回你想要替换的内容;如果文本没有匹配到,这个函数就不会被调用。你可以利用这个功能来处理你需要的内容,然后返回你想要替换成的固定字符串。这样就可以省去对正则表达式的第二次检查。
19
使用 re.subn
这个函数的作用和
sub()
一样,但它会返回一个元组(新字符串,替换的次数)。
然后你可以查看进行了多少次替换。例如:
text2, numReplacements = re.subn(pattern, repl, text1)
if numReplacements:
# did match
else:
# did not match