检查re.sub中是否发生修改 [英] Check whether modification in re.sub occurred
问题描述
Python 函数 re.sub(pattern, replacement, string)
返回修改后的字符串,其中匹配的模式被替换项替换.有没有什么简单的方法可以检查是否发生了匹配以及是否进行了修改?(还有,修改了多少)
取决于版本.在 Python <= 2.6 中,您必须将 sub()
与 match()
或 search()
结合起来以获得计数.
如果您使用的是 Python >= 2.7,您可以使用 subn()
,它将返回一个 (new_string, number_of_subs_made)
元组.
例如:
<预><代码>>>>进口重新>>>re.subn('l', 'X', "Hello World!")('HeXXo Word!', 3)The Python function re.sub(pattern, replacement, string)
returns the modified string with the matched pattern replaced with the replacement. Is there any easy way to check whether a match has occurred and a modification has been made? (And also, how many modifications)
Depends on the version. In Python <= 2.6, you have to couple sub()
with match()
or search()
to get count.
If you are using Python >= 2.7, you can use subn()
, which will return a tuple of (new_string, number_of_subs_made)
.
For example:
>>> import re
>>> re.subn('l', 'X', "Hello World!")
('HeXXo WorXd!', 3)
这篇关于检查re.sub中是否发生修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!