从斜杠分隔字符串中提取无括号函数名求助
解决方案
你的原正则返回null是因为它试图匹配function 前缀后的单词,但目标字符串里根本没有function 这个内容,自然匹配不到。要提取不带括号的函数名,可以用以下两种方法:
方法1:使用正向预查正则直接匹配
直接匹配后面紧跟()的单词,无需额外处理捕获组:
const myString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()'; const functionNames = myString.match(/\w+(?=\(\))/g); console.log(functionNames); // 输出:["getCustomer", "getCsvFileName", "getControllerName"]
正则解释:
\w+:匹配由字母、数字、下划线组成的函数名(符合JS函数名命名规则)(?=\(\)):正向预查,确保当前匹配的内容后面紧跟(),但不会将()包含在结果中
方法2:通过捕获组提取
如果需要对每个匹配结果做额外处理,可以用捕获组单独提取函数名:
const myString = 'my_doc/desktop/customer=getCustomer()/getCsvFileName()/controller=getControllerName()'; const regex = /(\w+)\(\)/g; let match; const results = []; while ((match = regex.exec(myString)) !== null) { results.push(match[1]); } console.log(results); // 输出:["getCustomer", "getCsvFileName", "getControllerName"]
这种方法通过循环调用exec,每次提取捕获组1的内容(即不带括号的函数名),适配需要逐个处理匹配项的场景。
内容的提问来源于stack exchange,提问作者Garry S
相关产品推荐
相关产品推荐

