javascript - 使用正则表达式匹配函数名称和参数
问题描述
我在以下模式中有一些字符串
'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'
解决方案
使用此正则表达式获取参数:
const argsRegex = /\(\s*([^)]+?)\s*\)/
获取数组中的参数:
const str = 'walkPath(left, down, left)'
const argsRegex = /\(\s*([^)]+?)\s*\)/
let res = str.match(argsRegex)
let args = res[1].split(", ")
推荐阅读
- encryption - 使用 PROC Groovy 的 AES - SAS CI
- sonarqube - SonarQube.Analysis.xml 被忽略
- selenium - Groovy,通过 span 或 div 查找对象
- dataframe - 如何解决pyspark数据帧中的编码问题
- java - HttpUrlConnection 超时问题适用于本地主机,但在使用远程 IP 时它不起作用
- visual-studio-code - F# Codelens 语言环境
- ckeditor - 将 file:// 链接插入富文本字段
- python-3.x - 将列标题合并到单个“标签”列中
- bootstrap-datepicker - 引导日期选择器中的键盘导航清除按钮和月份
- python - 如何在 python 游戏中添加音频?