bflemi3 bflemi3 - 2 months ago 22
Javascript Question

Regex matching comma delimited strings

Given any of the following strings, where operator and value are just placeholders:

"operator1(value)"
"operator1(value), operator2(value)"
"operator1(value), operator2(value), operator_n(value)"


I need to be able to match so i can get each operator and it's value as follows:

[[operator1, value]]
[[operator1, value], [operator2, value]]
[[operator1, value], [operator2, value], [operator_n, value]]


Please Note: There could be n number of operators (comma delimited) in the given string.

My current attempt will match on
operator1(value)
but nothing with multiple operators. See regex101 for the results.

/^(.*?)\((.*)\)$/

Answer

You should be able to do this with a single regex using the global flag.

var re= /(?:,\s*)?([^(]+?)\(([^)]+)\)/g;
var results = re.exec(str);

See the result at Regex 101: https://regex101.com/r/eC3uK3/2