Python RegEx multiple groups -
i'm getting confused returning multiple groups in python. regex this:
lun_q = 'lun:\s*(\d+\s?)*'
and string is
s = '''lun: 0 1 2 3 295 296 297 298'''`
i return matched object, , want @ groups, shows last number (258):
r.groups() (u'298',)
why isn't returning groups of 0,1,2,3,4
etc.?
your regex contains single pair of parentheses (one capturing group), 1 group in match. if use repetition operator on capturing group (+
or *
), group gets "overwritten" each time group repeated, meaning last match captured.
in example here, you're better off using .split()
, in combination regex:
lun_q = 'lun:\s*(\d+(?:\s+\d+)*)' s = '''lun: 0 1 2 3 295 296 297 298''' r = re.search(lun_q, s) if r: luns = r.group(1).split() # optionally, convert luns strings integers luns = [int(lun) lun in luns]
Comments
Post a Comment