查找字符串之间的重复模式

2024-10-03 23:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的列表:someList = ['blablahihix', 'somethinghihi'],我想返回一个列表,其中包含列表中两个元素之间的重复模式(在本例中为“hihi”)。你知道吗

下面是我要做的:

p, r = re.compile(r'(.+?)\1+'), []
for i in strList:
    r.extend(p.findall(i) or [i])

当我print r它给我['bla', 'hi', 'hi']。我想要的只是['hihi']。我不希望返回'blabla',因为我在列表的第二个元素中没有'blabla'。你知道吗

我错过了什么?你知道吗


Tags: inre元素列表for模式hicompile
1条回答
网友
1楼 · 发布于 2024-10-03 23:18:07

使用^{}操作获取匹配组的交集:

>>> strList = ['blablahihix', 'somethinghihi']
>>> p = re.compile(r'(.+?)\1+')

>>> [set(p.findall(i)) for i in strList]
[{'bla', 'hi'}, {'hi'}]

>>> # from functools import reduce  # In Python 3.x
>>> reduce(lambda a, b: a & b, (set(p.findall(i)) for i in strList))
{'hi'}

使用^{} or ^{}获得两个匹配中出现的公共部分。你知道吗


您需要修改模式或使用^{},因为^{}返回的方式取决于是否使用捕获组;如果模式中存在一个或多个组,则返回组列表,而不是整个匹配字符串的列表。你知道吗

>>> import re
>>>
>>> strList = ['blablahihix', 'somethinghihi']
>>> p = re.compile(r'(.+?)\1+')
>>> reduce(lambda a, b: a & b,
           (set(m.group() for m in p.finditer(i)) for i in strList))
{'hihi'}

更新

正如georg所建议的,您可以使用set.intersection(*...);不需要使用reduce。你知道吗

>>> set.intersection(*(set(m.group() for m in p.finditer(i)) for i in strList))
{'hihi'}

相关问题 更多 >