首页 > 解决方案 > 使用正则表达式匹配函数名称和参数

问题描述

我在以下模式中有一些字符串

'walkPath(left, down, left)'

为了单独提取函数名和另一个数组中的参数,我使用了这些正则表达式:

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' ] 

第一个工作正常。在第二个正则表达式中,来自 '(left' 的 '(' 应该被排除,所以它应该是 'left'

标签: javascriptregex

解决方案


使用此正则表达式获取参数:

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

获取数组中的参数:

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

推荐阅读