Matching function name and arguments using regex

Viewed 271

I have some strings in the following pattern

'walkPath(left, down, left)'

To extract the function name alone, and the arguments in an another array, i used those regular expressions:

const str = 'walkPath(left, down, left)'

const functionNameRegex = /[a-zA-Z]*(?=\()/
console.log(str.match(functionNameRegex)) //outputs ['walkPath'] ✅✅

const argsRegex = /(?![a-zA-Z])([^,)]+)/g
console.log(str.match(argsRegex)) //outputs [ '(left', ' down', ' left' ] 

the first one worked fine. In the second regex, the '(' from from '(left' should be excluded, so it should be 'left'

2 Answers

Use this regular expression for getting the arguments:

const argsRegex = /\(\s*([^)]+?)\s*\)/

For getting the arguments in an array:

const str = 'walkPath(left, down, left)'
const argsRegex = /\(\s*([^)]+?)\s*\)/
let res = str.match(argsRegex)
let args = res[1].split(", ")

Try this one:

/(?<=\((?:\s*\w+\s*,)*\s*)\w+/g

const str = 'walkPath(left, down, left)'

const functionNameRegex = /[a-zA-Z]*(?=\()/
console.log(str.match(functionNameRegex))

const argsRegex = /(?<=\((?:\s*\w+\s*,)*\s*)\w+/g
console.log(str.match(argsRegex))

It is not very restricted, if you really want to be safe, you can try:

/(?<=\w+\s*\((?:\s*\w+\s*,\s*)*\s*)\w+(?=\s*(?:\s*,\s*\w+\s*)*\))/g

Related