python - RegEx for matching multiple substrings using one group? -
i'm trying parse string unknown number of elements regex in python. here example:
>>>> import re >>>> re.match("\=( a([0-9]+))*", "= a1 a2 a3 a4").groups()[1::2] ('4',) i expect have:
('1', '2', '3', '4',) how can expected result?
edit:
re.findall not work me. let me make better example:
i want match following string:
_func(cmd, param1, param2, param3, param4)_ i don't know in advance nummber of parameters. expected solve using following code:
>>> re.match("(\w+)\(cmd(, (\w+))*\)", "func(cmd, param1, param2, param3, param4)") but not work, since groups ()* not expanded many items, last used. ideas?
pat = re.compile(r' a(\d+)') lst = re.findall(pat, "= a1 a2 a3 a4") this returns list, , in example showed tuple. presume list work you, of course can do:
t = tuple(lst) the answer gave doesn't check = in input string. if need that, can use 2 patterns , 2 steps:
pat0 = re.compile(r'=(?: a\d+)+') pat1 = re.compile(r' a(\d+)') m = pat0.search("= a1 a2 a3 a4") if not m: print("input string not expected") else: s = m.group(0) lst = re.findall(pat, s) edit: code handles func() example:
s_code = "func(cmd, param1, param2, param3, param4)" pat_recognize_args = re.compile(r'func\(cmd([^)]*)\)') pat_parse_args = re.compile(r'[, ]+([^, ]+)') m = pat_recognize_args.search(s_code) if m: s = m.group(1) lst = re.findall(pat_parse_args, s) when ran above code, lst set to: ['param1', 'param2', 'param3', 'param4']
pat_recognize_args looks literal string func literal ( (which backslash-escaped in pattern re won't try use start match group), literal string cmd, , match group matches literal ) character; match group closed ) , literal ) there match actual ) finishes function call. after pattern matches, match object have group 1 set interesting arguments function call.
so next set s = m.group(1) , have re.findall() pull out arguments us.
Comments
Post a Comment