如何计算字符串中子字符串的连续重复次数? [英] How to count consecutive repetitions of a substring in a string?

查看:65
本文介绍了如何计算字符串中子字符串的连续重复次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串中找到子字符串的连续(非重叠)重复.我可以计算它们但不是连续的.例如:

I need to find consecutive (non-overlapping) repetitions of a substring in a string. I can count them but not consecutive. For instance:

string = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"
substring = "AA"

这里,"AA" 在字符串的开头重复一次,然后是 4 次,然后是 2 次,以此类推.我应该选择最大的一个,在这个例子中 - 4 次.

here, "AA" is repeated one time at the beginning of the string, then 4 times, then 2 times, etc. I should select the biggest one, in this example - 4 times.

我该怎么做?

推荐答案

正则表达式 在搜索字符串时闪耀.在这里,您可以使用 (?:AA)+ 找到一个或多个 AA 的所有组,(?: 只是告诉引擎解释括号仅用于分组.

Regular expressions shine when searching through strings. Here you can find all groups of one or more AA with (?:AA)+ the (?: simply tells the engine to interpret the parentheses for grouping only.

一旦你有了组,你就可以使用 max() 根据长度找到最长的 (len()).

Once you have the groups you can use max() to find the longest based on length (len()).

import re

s = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"

groups = re.findall(r'(?:AA)+', s)
print(groups)
# ['AA', 'AAAAAAAA', 'AAAA', 'AA']

largest = max(groups, key=len)
print(len(largest) // 2)
# 4

这篇关于如何计算字符串中子字符串的连续重复次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆