129

我试图在 Python 2.6 中使用 re 在更大的数字系列中找到每 10 位数字系列。

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

在“123456789123456789”中

我应该得到以下列表:

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

我发现了对“前瞻”的引用,但是我看到的示例只显示了成对的数字而不是更大的分组,而且我无法将它们转换为两位数。

4

4 回答 4

220

在前瞻中使用捕获组。前瞻捕获您感兴趣的文本,但实际匹配在技术上是前瞻之前的零宽度子字符串,因此匹配在技术上是不重叠的:

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]
于 2011-04-11T04:58:06.667 回答
90

您也可以尝试使用支持重叠匹配的第三方regex模块(not re)。

>>> import regex as re
>>> s = "123456789123456789"
>>> matches = re.findall(r'\d{10}', s, overlapped=True)
>>> for match in matches: print(match)  # print match
...
1234567891
2345678912
3456789123
4567891234
5678912345
6789123456
7891234567
8912345678
9123456789
于 2013-09-23T19:06:51.290 回答
19

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

简单地

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
于 2011-07-27T13:34:12.350 回答
0

捎带接受的答案,以下目前也适用

import re
s = "123456789123456789"
matches = re.findall(r'(?=(\d{10}))',s)
results = [int(match) for match in matches]
于 2022-02-03T23:10:38.610 回答