想要对字符串中的连续数字进行计数
例如,如果我有:
s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7abb2a4a6b4a3b5a2f5f3f187a0aaa6aeabe9a4a8aa" rel="noreferrer noopener nofollow">[email protected]</a>'
d = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b565a49525a09085a554f54555e4f5a090b0a0f7b5c565a525715585456" rel="noreferrer noopener nofollow">[email protected]</a>'
字符串 s
的预期输出为 3。
字符串 d
的预期输出为 4,因为它是字符串内连续数字的最大数量
最佳答案
您可以使用re.findall
来获取连续的数字,并以max
和len
为key来获取最长的组
s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf0e9fffdeff8eef9aea8aadcfbf1fdf5f0b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>'
digits = re.findall(r"\d+", s)
print(len(max(digits, key=len))) # 3
如果您有一个没有数字的字符串,您可以使用 default
参数和长度为 0 的空列表
s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d51485e5c4e594f587d5a505c5451135e5250" rel="noreferrer noopener nofollow">[email protected]</a>'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0
关于python - 计算字符串中的连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72433900/