每次匹配组时检索

Retrieve every times a group matched

注:我用的是pypiregex模块

我有以下正则表达式模式(标记 V1 + VERBOSE):

(?(DEFINE)
  (?P<id>[\d-]+)
)
id:\s(?&id)(,\s(?&id))*

如何检索 <id> 组匹配的所有时间?

例如,在下面的文字中:

don't match this date: 2020-10-22 but match this id: 5668-235 as well as these id: 7788-58-2, 8688-25, 74-44558

我应该能够检索到以下值:

["5668-235", "7788-58-2", "8688-25", "74-44558"]

请注意 this regex 匹配模式,但我想在每次匹配特定组时进行检索(即使它在同一匹配对象中多次出现)。

DEFINE 块中使用的命名捕获组稍后在模式中用作构建块,当在消费模式部分中使用时,它们实际上并不捕获它们匹配的文本。

在这种特殊情况下,您可以使用

(?(DEFINE)
  (?P<id>[\d-]+)
)
id:\s+(?P<idm>(?&id))(?:,\s+(?P<idm>(?&id)))*

参见 this regex demo。重点是使用额外的命名捕获组,我将其命名为idm,您可以使用任何名称。

查看 Python demo:

import regex
pat = r'''(?(DEFINE)
  (?P<id>[\d-]+)
)
id:\s+(?P<idm>(?&id))(?:,\s+(?P<idm>(?&id)))*'''
text = r"don't match this date: 2020-10-22 but match this id: 5668-235 as well as these id: 7788-58-2, 8688-25, 74-44558"
print( [x.captures("idm") for x in regex.finditer(pat, text, regex.VERBOSE)] )
# => [['5668-235'], ['7788-58-2', '8688-25', '74-44558']]