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

如何用正则解析::name{参数}格式JS字符串并转换为对象?

自定义格式字符串转对象实现

核心思路

  • 先统一处理弯引号格式问题,将所有中文弯引号替换为标准英文双引号,降低后续匹配复杂度
  • 提取::名称{参数}结构中大括号包裹的参数字符串
  • 正则匹配所有键值对,批量存入对象

完整实现代码

function parseCustomFormatStr(inputStr) {
  // 替换所有中文弯引号为标准英文双引号
  const normalizedStr = inputStr.replace(/[“”]/g, '"');
  // 匹配提取大括号内的参数部分
  const paramsMatch = normalizedStr.match(/::[a-zA-Z0-9_]+\{([^}]*)\}/);
  
  // 格式不匹配或无参数时返回空对象
  if (!paramsMatch || !paramsMatch[1].trim()) {
    return {};
  }

  const paramsStr = paramsMatch[1].trim();
  const resultObj = {};
  // 匹配所有key="value"格式的键值对,支持值内包含空格、特殊符号
  const kvReg = /(\w+)\s*=\s*"([^"]*)"/g;
  let matchResult;

  while ((matchResult = kvReg.exec(paramsStr)) !== null) {
    const [, key, value] = matchResult;
    resultObj[key] = value;
  }

  return resultObj;
}

测试效果

// 输入示例(包含弯引号)
const str = `::app{port=”8080” display=”internal” name=”some name” route=”/“}`;
const result = parseCustomFormatStr(str);
console.log(result);
// 输出:
// {
//   port: "8080",
//   display: "internal",
//   name: "some name",
//   route: "/"
// }

兼容说明

  • 支持任意数量的自定义键值对
  • 自动兼容中文弯引号、英文双引号两种引号格式
  • 支持参数值包含空格、斜杠等普通特殊字符
  • 格式不匹配时安全返回空对象,不会抛出异常

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:09:02