JavaScript中如何按带条件正则拆分字符串并转为对象数组
命令行参数拆分解决方案
正则表达式
直接用这个正则就能精准匹配你的参数格式:
/(?:^|\s)(-{1,2}\w+)(?:\s+(".*?"|\S+))?/g
拆解下各部分作用:
(?:^|\s):匹配字符串开头或者空格,用来定位参数的起始位置,不会捕获成多余的分组(-{1,2}\w+):捕获1到2个连字符开头、后面跟字母数字的参数名(单连、双连开头都能匹配)(?:\s+(".*?"|\S+))?:匹配参数名后的空格,然后要么是带双引号的多空格内容,要么是无空格的单个值,整个组为可选(兼容无值的参数场景)
代码实现
把匹配结果转成你需要的对象数组,用这个函数即可:
function parseArgs(str) { const regex = /(?:^|\s)(-{1,2}\w+)(?:\s+(".*?"|\S+))?/g; // 提取所有匹配项 const matches = [...str.matchAll(regex)]; // 转换为目标格式 return matches.map(match => { let value = match[2] || ''; // 移除值两端的双引号 if (value.startsWith('"') && value.endsWith('"')) { value = value.slice(1, -1); } return { name: match[1], value: value.trim() }; }); } // 测试示例 const example1 = `--filename test_layer_123.png`; const example2 = `--code 1 --level critical -info "This is some info"`; console.log(parseArgs(example1)); // 输出: [{ name: "--filename", value: "test_layer_123.png" }] console.log(parseArgs(example2)); // 输出: [ // { name: "--code", value: "1" }, // { name: "--level", value: "critical" }, // { name: "-info", value: "This is some info" }, // ]
补充说明
- 正则无需额外区分单连字符和双连字符,自动适配两种格式
- 支持带双引号的多空格参数值,会完整提取内容并自动去除引号
- 用
matchAll比split更适合这类键值对提取场景,避免拆分后的数据混乱
内容的提问来源于stack exchange,提问作者Yildirim
相关产品推荐
相关产品推荐

