How can a log parser expose field positions for named capture groups?
A compiled pattern's groupindex maps capture names to group numbers, exposing how the parsed fields are organized.
Python example and interpretation
Named fields run and score map to groups one and two. Inserting another capture can shift numbers, making name-based access easier to maintain.
import re
p=re.compile(r'(?P<run>[A-Z]+):(?P<score>[0-9]+)')
dict(p.groupindex)Result {'run': 1, 'score': 2}
中文
日志解析器怎样导出命名捕获组对应的字段编号?
编译后正则的 groupindex 是组名到组号的映射,可用于检查解析输出是否符合字段契约。
Python 算例与适用条件
为 run 和 score 命名后可发现它们是第 1、2 组。如果中间插入其他捕获组,编号可能变化,按名读取更便于维护。
import re
p=re.compile(r'(?P<run>[A-Z]+):(?P<score>[0-9]+)')
dict(p.groupindex)结果 {'run': 1, 'score': 2}