title: Regular expression to match function name and all arguments in Python
body: <p>Suppose I have a string such as the following:</p>
  
  <pre><code>"func(arg1, arg2, arg3, arg4, ..., argn)"
  </code></pre>
  
  <p>EDIT: This function is not in some particular language. It just has this format. If it makes it easier, don't think of it as a function call, just a string.</p>
  
  <p>I want to write a regular expression to match the function and <strong>each</strong> of the arguments. I am writing this in Python. The desired output of this is:</p>
  
  <pre><code>{"function" : "func", "arg" : ["arg1", "arg2", ... , "argn"]}
  </code></pre>
  
  <p>EDIT: While the arguments could be function calls, I can easily recursively try to match them with the same regular expression once I create one that works. By this I mean I can recurse on the function with each of the arguments. But this is not really relevant. I am <strong>not</strong> trying to create an interpreter, just something to recognize the arguments.</p>
  
  <p>Here is my attempt at this:</p>
  
  <pre><code>import re
  s = "func(arg1, arg2, arg3, arg4, argn)"
  m = re.match(r"(?P&lt;function&gt;\w+)\s?\((?P&lt;args&gt;(?P&lt;arg&gt;\w+(,\s?)?)+)\)", s)
  print m.groupdict()
  </code></pre>
  
  <p>And here is the output:</p>
  
  <pre><code>{'function': 'func', 'args': 'arg1, arg2, arg3, arg4, argn', 'arg': 'argn'}
  </code></pre>
  
  <p>The function matches just fine, and so does the argument set. However, I can't seem to match the individual arguments. Is this a problem with my regex, or a limitation of Python regular expression matching?</p>
  
  <p>EDIT2: I am aware that I can now split the arguments using the following code:</p>
  
  <pre><code>d["arg"] = d["args"].split(", ")
  </code></pre>
  
  <p>But I was wondering if I could do the whole job with regular expressions. In particular, I am wondering why "arg" is matched to only the last argument.</p>
  
  <p>EDIT3: I guess I am (1) hoping to figure out why Python only matches the last argument every time, and (2) whether I can do Scheme-style pattern-matching in Python. Or if there is something just as intuitive in Python as Scheme-style pattern matching. I looked at the ast module, and its syntax is prohibitively complex.</p>