python - Get the spans of named groups in order in one line -


i have regex r'(?p<mark1>)|\s+(?p<mark2>)|(?p<mark3>)\s+' (sample regex not actual one) , want spans of captured groups in matches in order.

for example:
1. [match.span() match in re.finditer(regex, string)] returns spans in order gives span of whole match not captured group.
2. [match.span('mark1') match in re.finditer(regex, string)] returns spans in order of captured groups puts (-1, -1) other named groups.

so, can spans of named groups in order of matches in 1 line, simple above queries?

i found following way:
[match.span(name) match in re.finditer(regex, string) name, value in match.groupdict().items() if value not none]

is there simple one?

an example present scenario:

import re s = "asfasdf      32392  ..///?%        aslf    /././/               342" reg = r'(?p<mark1>[a-z]+)|\s+(?p<mark2>[0-9]+)|(?p<mark3>[./?%]+)\s+' print([match.span(name) match in re.finditer(reg, s) name, value in match.groupdict().items() if value not none]) print([match.span() match in re.finditer(reg, s)]) print print([match.span('mark1') match in re.finditer(reg, s)]) print([match.span('mark2') match in re.finditer(reg, s)]) print([match.span('mark3') match in re.finditer(reg, s)]) 

output:

[(0, 7), (13, 18), (20, 27), (35, 39), (43, 49)] [(0, 7), (7, 18), (20, 35), (35, 39), (43, 64)]  [(0, 7), (-1, -1), (-1, -1), (35, 39), (-1, -1)] [(-1, -1), (13, 18), (-1, -1), (-1, -1), (-1, -1)] [(-1, -1), (-1, -1), (20, 27), (-1, -1), (43, 49)] 


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -