Python正则表达式找到所有重叠匹配项?

2024-06-11 16:29:00 发布

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

我试图在Python2.6中使用re在一个更大的数字序列中找到每个10位数字序列。

我很容易抓住没有重叠的匹配,但我想在数字序列中的每一个匹配。例如

在“123456789123456789”中

我应该得到以下清单:

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

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


Tags: re示例序列数字lookahead两位数
3条回答

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

简单地

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

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

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]

您还可以尝试使用third-party ^{} module(而不是re),它支持重叠匹配。

>>> 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

相关问题 更多 >