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

+3


source to share


2 answers


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);
      

Run code




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)

.

0


source


The regex /\((\w+(?:,\s?\w+)?)\)/

will return a, b

for func(a, b)

as well as a,b,c

forfunc(a,b,c)



Hopefully this is what you wanted, depending on what language you do it in, you can just split them up each ,

one to put them in an array for indexing later.

0


source







All Articles