Python:重新找到最长的序列

Nop*_*ope 2 python regex

我有一个随机生成的字符串:

polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
Run Code Online (Sandbox Code Playgroud)

我想找到最长的"diNCO二醇"序列和最长的"diNCO二胺"序列.因此,在上述情况下,最长的"diNCO二醇"序列为1,最长的"diNCO二胺"为3.

我将如何使用python的re模块进行此操作?

提前致谢.

编辑:
我的意思是给定字符串的最长重复次数.因此,含有"diNCO二胺"的最长的链是3:
二醇二-NCO二胺二-NCO二胺二-NCO二胺硝基二醇二硝二胺

tgr*_*ray 5

扩展Ealdwulf答案:

文档re.findall可以在这里找到.

def getLongestSequenceSize(search_str, polymer_str):
    matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str)
    longest_match = max(matches)
    return longest_match.count(search_str)
Run Code Online (Sandbox Code Playgroud)

这可以写成一行,但在那种形式下变得不那么可读.

替代方案:

如果polymer_str是巨大的,它将使用更高的内存效率re.finditer.以下是您可以采用的方法:

def getLongestSequenceSize(search_str, polymer_str):
    longest_match = ''
    for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str):
        if len(match.group(0)) > len(longest_match):
            longest_match = match.group(0)
    return longest_match.count(search_str)
Run Code Online (Sandbox Code Playgroud)

findall和之间的最大区别finditer是第一个返回列表对象,而第二个迭代匹配对象.此外,这种finditer方法会稍慢.