Python的正则expression式查找所有重叠的匹配?

我试图在Python 2.6中使用re来查找更大数字序列中的每个10位数字序列。

我很容易抓住没有重叠的比赛,但我希望数字系列中的每一场比赛。 例如。

在“123456789123456789”

我应该得到以下列表:

[1234567891,2345678912,3456789123,4567891234,5678912345,6789123456,7891234567,8912345678,9123456789] 

我发现引用了一个“向前看”,但是我所见过的例子只显示了数字对而不是更大的分组,而我还没有能够将它们转换为两位数以外的数字。

 import re s = "123456789123456789" matches = re.finditer(r'(?=(\d{10}))',s) results = [int(match.group(1)) for match in matches] # results: # [1234567891, # 2345678912, # 3456789123, # 4567891234, # 5678912345, # 6789123456, # 7891234567, # 8912345678, # 9123456789] 

您也可以尝试使用支持重叠匹配的新Python正则expression式模块 。

 >>> import regex as re >>> s = "123456789123456789" >>> matches = re.findall(r'\d{10}', s, overlapped=True) >>> for match in matches: print match ... 1234567891 2345678912 3456789123 4567891234 5678912345 6789123456 7891234567 8912345678 9123456789 

我喜欢正则expression式,但是这里不需要它们。

只是

 s = "123456789123456789" n = 10 li = [ s[i:i+n] for i in xrange(len(s)-n+1) ] print '\n'.join(li) 

结果

 1234567891 2345678912 3456789123 4567891234 5678912345 6789123456 7891234567 8912345678 9123456789