Home > Blockchain >  Regex for parsing functions and their optional arguments in parenthesis
Regex for parsing functions and their optional arguments in parenthesis

Time:04-14

I'm very close to having this regex work the way I want it to. My regex is:

const text = 'func0 func-1(1)    func-2(1, 2) func3';
const matches = text.matchAll(\s*([^(]*)(?:\(([^\)] )\))?)

I need this to parse out to multiple groups where group 1 is the function name (ex func0) and group 2 is the arguments if they exist. Arguments and parenths are not required.

This example should give me the matches:

Match 0: 'func0'
Group 0: 'func0'
Group 1: ''

Match 0: 'func1'
Group 0: 'func1'
Group 1: '1'

Match 0: 'func2'
Group 0: 'func2'
Group 1: '1, 2'

Match 0: 'func3'
Group 0: 'func3'
Group 1: ''

My regexp currently only works if there all functions have params and/or if a argumentless function is last and it can be the only one.

My issue really is just with how to optionally allow the arguments for any function anywhere in the string. I need to check if a space is found before a parenthesis and if so end the match group.

Here is an example regex: https://regexr.com/6jiv2

CodePudding user response:

I think this gives what you're looking for. The only material difference is that "Group 1" for a function without arguments returns null instead of ''.

const text = "func0 func-1(1)    func-2(1, 2) func3";
const matches = [...text.matchAll(/([^ \(] )(?:\(([^\)] )\))?/g)];
console.log(JSON.stringify(matches));

// [["func0","func0",null],["func-1(1)","func-1","1"],["func-2(1, 2)","func-2","1, 2"],["func3","func3",null]]

CodePudding user response:

I slightly modified your regex to this: \s*(?<fname>[^ (] )(?:\((?<args>[^\)] )\))?

Test here:

With this you can use named groups, to access the function name and the arguments separately.

The following are Match, group1(fname) and group2(args):

Match 0: 'func0'
fname: 'func0'
args: ''

Match 0: 'func1'
fname: 'func1'
args: '1'

Match 0: 'func2'
fname: 'func2'
args: '1, 2'

Match 0: 'func3'
fname: 'func3'
args: ''
  • Related