Parsing a function call using python regex

Viewed 116

I am attempting to parse a function call:

foo(arg1, arg2 ...)

to match for foo, arg1, arg2. But the issue I'm having is, arg1 may be bar(x1, x2) with commas inside.

When I use this tool with ([\w]+)\((.*?)\)$ as my regex and foo(bar(2,'a'), bas()) as my test case, I'm able to capture foo and the entire line of arguments bar(2,'a'), bas(), but I'm not sure how to capture the arguments separately.

I would like to capture:

  • foo
  • bar(2,'a')
  • bas()

How do I revise my python regex to capture these argument separately?

1 Answers

Try this regex: ([\w]+)\((.*?), (.*?)\)$. It will work for two arguments. See the testing here

  • (.*?) - finds the shortest possible argument
  • , - , (separates the argument)
  • (.*?) - finds the second argument

If you want it to be dynamic with 1+ number of arguments, you can use the following regex: ([\w]+)\((.*?)(?:, (.*?))*\)$. See the testing here

  • (.*?) - finds the shortest first possible argument
  • (?:, (.*?))* - finds the next 0-n number of , (.*?)
    • , - matches , literally but does not capture
    • (.*?) - matches another argument
Related