[英]python 3 regex - find all overlapping matches' start and end index in a string
[英]How to use regex to find all overlapping matches
我試圖在 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]
您也可以嘗試使用支持重疊匹配的第三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
我喜歡正則表達式,但這里不需要它們。
簡單地
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
捎帶接受的答案,以下目前也適用
import re
s = "123456789123456789"
matches = re.findall(r'(?=(\d{10}))',s)
results = [int(match) for match in matches]
常規方式:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.