Home > Back-end >  match a pattern in text and read it to different variables
match a pattern in text and read it to different variables

Time:10-24

I have the following pattern: <num1>-<num2> <char a-z>: <string>. For example, 1-3 z: zztop

I'd like to parse them to n1=1, n2=3, c='z', s='zztop'

Of course I can do this easily with splitting but is there a more compact way to do that in Python?

CodePudding user response:

Using re.finditer with a regex having named capture groups:

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'}]
  • Related