REGEX - 使用finditer()

时间:2015-09-12 05:27:52

标签: python regex

假设我有一个字符串abbb。我正在尝试使用正则表达式进行打印以执行以下模式:

a
ab
abb
abbb

我试过

import re
line= "abbb"
m = re.finditer('ab*',line)
for i in m:
    print i.group(1)

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

2 个答案:

答案 0 :(得分:1)

Regex不会帮助您实现您想要的目标。 对于ab*等模式和abbbbb之类的模式,您可以执行以下操作:

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

<强>输出

a
ab
abb
abbb

请注意,这是一个特例,它可能不会成为更复杂模式的好解决方案!

使用正则表达式

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

<强>输出

a
ab
abb
abbb

答案 1 :(得分:1)

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

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