匹配文本中的模式并将其读取到不同的变量
match a pattern in text and read it to different variables
我有以下模式:<num1>-<num2> <char a-z>: <string>
。例如,1-3 z: zztop
我想将它们解析为 n1=1, n2=3, c='z', s='zztop'
当然,我可以通过拆分轻松做到这一点,但是在 Python 中有更紧凑的方法吗?
将 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'}]
我有以下模式:<num1>-<num2> <char a-z>: <string>
。例如,1-3 z: zztop
我想将它们解析为 n1=1, n2=3, c='z', s='zztop'
当然,我可以通过拆分轻松做到这一点,但是在 Python 中有更紧凑的方法吗?
将 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'}]