string = "input-ports 6012, 6017, 6016"
m = re.match("input-ports(\s\d{4},?)(\s\d{4},?)(\s\d{4},?)", string)
print m.groups #=> (' 6012,', ' 6017,', ' 6016')
Run Code Online (Sandbox Code Playgroud)
但是当我想使用组重复时,它只返回最后一个数字
m = re.match("input-ports(\s\d{4},?)+", string)
print m.groups #=> (' 6016',)
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这是为什么?
虽然传统的正则表达式引擎只记住并返回最后一个匹配项,但一些高级库提供了保存captures给定组的所有匹配项的属性。有一个名为regexpython 的库可以做到这一点,还有其他一些好处:
import regex
string = "input-ports 6012, 6017, 6016"
m = regex.match("input-ports(?:\s(\d{4}),?)+", string)
print m.captures(1) # ['6012', '6017', '6016']
Run Code Online (Sandbox Code Playgroud)
如果您无法使用此库,唯一的解决方法是使用findall具有前瞻功能的单个组并将其替换为重复。这并不总是可能的,但你的例子很简单:
import re
string = "input-ports 6012, 6017, 6016"
m = re.findall("(?<=\s)\d{4}(?=,|$)", string)
print m # ['6012', '6017', '6016']
Run Code Online (Sandbox Code Playgroud)