如何计算字符串中连续字符串组的最大数量?
import re
s = "HELLOasdHELLOasdHELLOHELLOHELLOasdHELLOHELLO"
# Give me the max amount of consecutive HELLO groups ---> wich is 3
# There's a group of 3 and a group of 2, but 3 is the max.
count = re.findall("(HELLO)+", s) # count is: ['HELLO', 'HELLO', 'HELLO', 'HELLO']
count = len(count)
print(count)
输出是:
4
这是完全错误的。连续 HELLO 的最大数量为 3。
我认为我使用了错误的 RE,而且我不知道如何计算这些重复次数以找到最大值。
我不明白为什么输出是4。
Thanks!
您需要捕获连续的整个字符串HELLO
s 在你的比赛中;那么你可以计算出HELLO
s 将匹配字符串的长度除以 5(HELLO
)。使用列表理解:
import re
s = "HELLOasdHELLOasdHELLOHELLOHELLOasdHELLOHELLO"
print(max([len(x) // 5 for x in re.findall(r'((?:HELLO)+)', s)]))
Output
3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)