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

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

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

在“ 123456789123456789”中

我应该得到以下列表:

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

我已经找到了对“超前”的引用,但是我所看到的示例仅显示了成对的数字,而不是更大的分组,而且我无法将其转换为两位数以外的数字。

I’m trying to find every 10 digit series of numbers within a larger series of numbers using re in Python 2.6.

I’m easily able to grab no overlapping matches, but I want every match in the number series. Eg.

in “123456789123456789”

I should get the following list:

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

I’ve found references to a “lookahead”, but the examples I’ve seen only show pairs of numbers rather than larger groupings and I haven’t been able to convert them beyond the two digits.


回答 0

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

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]

Use a capturing group inside a lookahead. The lookahead captures the text you’re interested in, but the actual match is technically the zero-width substring before the lookahead, so the matches are technically non-overlapping:

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]

回答 1

您也可以尝试使用支持重叠匹配(不是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

You can also try using the (not re), which supports overlapping matches.

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

回答 2

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

只是

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

I’m fond of regexes, but they are not needed here.

Simply

s =  "123456789123456789"

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

result

1234567891
2345678912
3456789123
4567891234
5678912345
6789123456
7891234567
8912345678
9123456789

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。