Split string that looks like a Python function call to arguments -


i trying make function accepts string looks function call in python , returns arguments function example:

"fun(1, bar(x+17, 1), arr = 's,y')" 

will result:

["1", "bar(x+17, 1)", "arr = 's,y'"] 

the problem of using regular expressions don't know if possible not split @ commas inside parenthesis or quotes. thanks.

edit: python: splitting function , arguments doesn't answer correctly quastions since doesn't treat commas in parenthesis or quotes.

as @kevin said, regular expressions cannot solve this since can't handle nested parenthesis.

you can keep track of own state

def parse_arguments(s):     openers = "{[\"'("     closers = "}]\"')"     state = []     current = ""     c in s:         if c == "," , not state:            yield current            current = ""         else:            current += c            if c in openers:               state.append(c)            elif c in closers:               assert state, "error no opener %s"%c               assert state[-1] == openers[closers.index(c)],"error mismatched %s %s"%(state[-1],c)               state.pop(-1)     assert not state, "error unexpected end, expected %s"%state[-1]     yield current  print list(parse_arguments("1, bar(x+17, 1), arr = 's,y'")) 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -