【发布时间】:2021-10-23 09:08:43
【问题描述】:
我有以下模式:<num1>-<num2> <char a-z>: <string>。例如1-3 z: zztop
我想将它们解析为n1=1, n2=3, c='z', s='zztop'
当然,我可以通过拆分轻松地做到这一点,但是在 Python 中是否有更紧凑的方法来做到这一点?
【问题讨论】:
标签: python-3.x regex parsing
我有以下模式:<num1>-<num2> <char a-z>: <string>。例如1-3 z: zztop
我想将它们解析为n1=1, n2=3, c='z', s='zztop'
当然,我可以通过拆分轻松地做到这一点,但是在 Python 中是否有更紧凑的方法来做到这一点?
【问题讨论】:
标签: python-3.x regex parsing
将re.finditer 与具有命名捕获组的正则表达式一起使用:
inp = "1-3 z: zztop"
r = re.compile('(?P<n1>[0-9]+)-(?P<n2>[0-9]+) (?P<c>\w+):\s*(?P<s>\w+)')
output = [m.groupdict() for m in r.finditer(inp)]
print(output) # [{'n1': '1', 'n2': '3', 'c': 'z', 's': 'zztop'}]
【讨论】: