Python 如何在字符串中查找子字符串的最大连续出现次数?
我想要一个函数,它将接受一个完整字符串和一个子字符串,并返回该子字符串的最大连续出现次数。我知道我必须使用正则表达式,但我对语法不是很熟悉,我有点卡住了 所以它应该是这样工作的:Python 如何在字符串中查找子字符串的最大连续出现次数?,python,regex,Python,Regex,我想要一个函数,它将接受一个完整字符串和一个子字符串,并返回该子字符串的最大连续出现次数。我知道我必须使用正则表达式,但我对语法不是很熟悉,我有点卡住了 所以它应该是这样工作的: import re def get_max(substring, fullstring): ???? #TO-DO return max print(get_max(foo, foofoofooxxfoofoo) Output: 3 使用re: import re def ge
import re
def get_max(substring, fullstring):
???? #TO-DO
return max
print(get_max(foo, foofoofooxxfoofoo)
Output: 3
使用re
:
import re
def get_max(substring, full_string):
pattern = "(?=((" + re.escape(substring) + ")+))"
matches = re.findall( pattern, full_string )
return max(len(m[0]) // len(substring) for m in matches
print(get_max('foo', 'foofoofooxxfoofoo'))
输出:
3
Stackoverflow不是一种编程服务。你试过什么,为什么不奏效?