2

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 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'm going to accept this one because it has less lines of code, thanks.
1

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(", ")

2 Comments

Thanks for the answer but it did not work, the arguments should be in an array like ['left', 'down', 'left']
@FayezNazzal I had updated the code to get the arguments in an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.