使用finditer()的正则表达式

2024-10-03 02:37:31 发布

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

假设我有一个字符串abbb。我尝试使用regex打印以执行以下模式:

a
ab
abb
abbb

我试过了

^{pr2}$

这不起作用。在python文档中,他们说ab*将匹配aab,或者{},后跟任意数量的{}。我当时想{}将把所有不同的匹配项存储在一个类似{a,ab,...,abbb}的列表中。网络中finditer()的例子非常有限。我怎样才能做到这一点?请注意,我需要使用正则表达式。在


Tags: 字符串文档网络列表数量ab模式例子
2条回答

Regex不会帮助您实现您想要的。 对于像ab*这样的模式和abbbbb这样的行,您可以这样做:

from itertools import combinations
line= "abbb"
for x in range(1, len(line)+1):
    print "".join(list(combinations(line, x))[0])

输出

^{pr2}$

请注意,这是一个特殊情况,对于更复杂的模式,它可能不是一个好的解决方案!在


使用正则表达式

import re

text= "abbb"
pattern = re.compile('ab*')

e = 1
while True and e < len(text)+1:
    match = pattern.search(text, 0, e)
    if not match:
        break
    s = match.start()
    print text[s:e]
    e += 1

输出

^{pr2}$

另一种正则表达式方法,它反转前面的字符串,并使用包含在lookahead中的反向模式来获得重叠匹配:

>>> s = 'abbb'
>>> [i[::-1] for i in reversed(re.findall(r'(?=(b*a))', s[::-1]))]

相关问题 更多 >