如何使用正则表达式查找所有重叠的匹配项

问题描述 投票:0回答:5

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

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

在“123456789123456789”中

我应该得到以下列表:

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

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

python regex overlapping
5个回答
246
投票

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

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]

97
投票

您也可以尝试使用第三方

regex
模块(不是
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

16
投票

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

简单

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

3
投票

搭载已接受的答案,以下目前也有效

import re
s = "123456789123456789"
matches = re.findall(r'(?=(\d{10}))',s)
results = [int(match) for match in matches]

0
投票

常规方式:

import re


S = '123456789123456789'
result = []
while len(S):
    m = re.search(r'\d{10}', S)
    if m:
        result.append(int(m.group()))
        S = S[m.start() + 1:]
    else:
        break
print(result)
© www.soinside.com 2019 - 2024. All rights reserved.