Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to parse Javascript function call-like syntax

I have the following data posibilities

fnname()
fnname(value)
fnname(value,valueN)

I need a way to parse it with javascript regex to obtain an array

[fnname]
[fnname,value]
[fnname,value,valueN]

Thanks in advance!

like image 536
rnrneverdies Avatar asked Feb 13 '23 04:02

rnrneverdies


2 Answers

You could try matching rather than splitting,

> var re = /[^,()]+/g;
undefined
> var matches=[];
undefined
> while (match = re.exec(val))
... {
... matches.push(match[0]);
... }
5
> console.log(matches);
[ 'fnname', 'value', 'value2', 'value3', 'value4' ]

OR

> matches = val.match(re);
[ 'fnname',
  'value',
  'value2',
  'value3',
  'value4' ]
like image 200
Avinash Raj Avatar answered Feb 15 '23 11:02

Avinash Raj


This should work for you:

var matches = string.split(/[(),]/g).filter(Boolean);
  • Regex /[(),]/g is used to split on any of these 3 characters in the character class
  • filter(Boolean) is used to discard all empty results from resulting array

Examples:

'fnname()'.split(/[(),]/g).filter(Boolean);
//=> ["fnname"]

'fnname(value,value2,value3,value4)'.split(/[(),]/g).filter(Boolean);
//=> ["fnname", "value", "value2", "value3", "value4"]
like image 45
anubhava Avatar answered Feb 15 '23 11:02

anubhava