JavaScript如何将::name{参数...}格式字符串转为字典并校验格式
JavaScript自定义格式字符串解析实现
完整可运行代码
function parseCustomFormatStr(str) { // 第一步:整体格式校验 const fullPattern = /^::\w+\{([\s\S]*)\}$/; const fullMatch = str.match(fullPattern); if (!fullMatch) { throw new Error('输入格式不符合::name{parameters...}结构要求'); } const paramsStr = fullMatch[1]; const result = {}; // 匹配所有key="value"格式键值对,兼容等号前后的空格 const paramPattern = /(\w+)\s*=\s*"([^"]*)"/g; let match; while ((match = paramPattern.exec(paramsStr)) !== null) { const key = match[1]; const value = match[2]; result[key] = value; } // 可选校验:参数部分非空但无合法键值对时抛出错误 if (paramsStr.trim() !== '' && Object.keys(result).length === 0) { throw new Error('大括号内参数格式不合法,需为key="value"格式的键值对'); } return result; }
使用示例
// 合法输入测试 const str = '::student{name="this is the name" age="21" faculty="some faculty"}' const dic = parseCustomFormatStr(str); console.log(dic); // 输出:{ name: 'this is the name', age: '21', faculty: 'some faculty' } // 非法输入测试 try { parseCustomFormatStr('student{name="test"}'); // 缺少::前缀 } catch (e) { console.log(e.message); // 输出:输入格式不符合::name{parameters...}结构要求 }
兼容特性
- 支持键值对之间任意数量的空格分隔
- 支持等号前后存在空格的格式
- 支持value中包含空格、特殊字符(双引号除外)的场景
- 自动忽略大括号内的首尾空格
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

