如何用正则从{key=value,...}格式字符串提取键值对并转为对象
提取格式化字符串中的键值对并转换为JS对象
步骤1:预处理原始字符串
原始字符串包含外层的引号和大括号,先剔除这些多余字符,只保留内部的键值对内容:
const rawStr = '"{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}"'; const content = rawStr.slice(2, -2); // 去掉开头的"{和结尾的}"
步骤2:正则匹配键值对
用正则表达式匹配所有键值对,兼顾普通值(字符串/数字)和数组类型的值:
const regex = /(\w+)\s*=\s*(\[[^\]]+\]|\d+|\w+)/g; const matches = [...content.matchAll(regex)];
正则说明:
(\w+):匹配键名(字母、数字、下划线)\s*=\s*:匹配等号,允许前后存在空格(\[[^\]]+\]|\d+|\w+):匹配三种类型的值:\[[^\]]+\]:匹配数组格式(如[40,40,40,40])\d+:匹配纯数字\w+:匹配字符串(如svg)
步骤3:转换值类型并构建对象
遍历匹配结果,对每个值做类型转换,最终组装成目标对象:
const result = {}; matches.forEach(([_, key, value]) => { if (value.startsWith('[')) { // 处理数组:去掉括号,分割后转为数字数组 result[key] = value.slice(1, -1).split(',').map(item => parseInt(item.trim(), 10)); } else if (!isNaN(Number(value))) { // 处理数字 result[key] = Number(value); } else { // 处理字符串 result[key] = value; } }); console.log(result);
运行后得到的结果与需求一致:
{ format: 'svg', width: 383, height: 480, transform: [40, 40, 40, 40], scaleX: 1, scaleY: 1 }
完整代码整合
const rawStr = '"{format=svg, width=383, height=480, transform=[40, 40, 40, 40], scaleX=1, scaleY=1}"'; const content = rawStr.slice(2, -2); const regex = /(\w+)\s*=\s*(\[[^\]]+\]|\d+|\w+)/g; const matches = [...content.matchAll(regex)]; const result = {}; matches.forEach(([_, key, value]) => { if (value.startsWith('[')) { result[key] = value.slice(1, -1).split(',').map(item => parseInt(item.trim(), 10)); } else if (!isNaN(Number(value))) { result[key] = Number(value); } else { result[key] = value; } }); console.log(result);
内容的提问来源于stack exchange,提问作者hyphens2
相关产品推荐
相关产品推荐

