我有以下模式:<num1>-<num2> <char a-z>: <string>。例如,1-3 z: zztop
我想決議它們 n1=1, n2=3, c='z', s='zztop'
當然,我可以通過拆分輕松地做到這一點,但是在 Python 中是否有更緊湊的方法來做到這一點?
uj5u.com熱心網友回復:
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'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334537.html
