You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:36:05