如何检查 re.sub() 是否已在 python 中成功替换? [英] How to check if re.sub() has successfully replaced in python?

查看:25
本文介绍了如何检查 re.sub() 是否已在 python 中成功替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 re.sub() 返回整个修改/未修改的字符串,有没有办法检查 re.sub() 是否已成功修改文本,而不需要搜索 re.sub() 的输出?

解决方案

您可以使用 re.subn 执行与 sub() 相同的操作,但返回一个元组 (new_string, number_of_subs_made)

如果修改次数为0,即不修改字符串.

<预><代码>>>>re.subn('(xx)+', '', 'abcdab')('abcdab', 0)>>>re.subn('(ab)+', '', 'abcdab')('cd', 2)>>>

Since re.sub() returns the whole modified/unmodified string, is there any way to check if re.sub() has successfully modified the text, without searching the output of re.sub()?

解决方案

You can use re.subn which perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made)

If number of modification is 0 i.e. string is not modified.

>>> re.subn('(xx)+', '', 'abcdab')
('abcdab', 0)
>>> re.subn('(ab)+', '', 'abcdab')
('cd', 2)
>>> 

这篇关于如何检查 re.sub() 是否已在 python 中成功替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆