Retrieving Arguments Using Regular Expressions
I am trying to use regex to extract arguments from a function definition into an array. for example
func(a) -> ['a']
func(a,b) -> ['a','b']
func(a, b) -> ['a','b']
The regex below correctly matches the argument block
/\((?:(\w+),?\s*)+\)/
However, only the last matched capture group is returned, i.e. the results are:
func(a) -> ['a']
func(a,b) -> ['b']
func(a,b,c) -> ['c']
This seems to be a generally useful model for capturing a portion of a repeating block. Is there a way to correctly achieve the expected result?
My saved session regexr can be found here
source to share
You can get arguments like this:
var s = "func(a, b, c )";
var res = s.substring(s.indexOf("(") + 1, s.indexOf(")")).split(/\s*,\s*/g);
alert(res);
This will work if you have independent strings like the ones in your example input.
And another way that I was trying to add is to output the brace group using a regex /\(([^()]+)\)/
and then split the contents of the captured group 1 by .split(/\s*,\s*/g)
.
source to share