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

如何使用JavaScript解析包含双大括号的字符串?

问题

有没有快速的正则表达式方法或者类似方案,能把字符串解析成两类内容:不在双大括号里的「静态」部分,以及在双大括号里的「动态」部分?

示例输入

Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}.

期望输出

[
  {
    type: "static",
    value: "Lorem "
  },
  {
    type: "dynamic",
    value: "ipsum dolor sit"
  },
  {
    type: "static",
    value: " amet, {consectetur} adipiscing "
  },
  {
    type: "dynamic",
    value: "elit"
  },
  {
    type: "static",
    value: "."
  },
]

当前尝试的问题

我用正则/\{*([^{}]+)\}*/g结合while循环和exec方法解析,但这个方法会错误地把任意数量的大括号内容当成动态值,示例代码如下:

function templateParser(string) {
  const re = /\{*([^{}]+)\}*/g;

  const output = [];

  while (true) {
    const match = re.exec(string);

    if (!match) {
      break;
    }

    const [templateItem, templateKey] = match;

    output.push({
      type: templateItem === templateKey ? "static" : "dynamic",
      value: templateItem === templateKey ? templateItem : templateKey
    });
  }

  return output;
}

console.log(
  templateParser(
    "Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}."
  )
);

解决方案

可以用一个更精准的正则表达式,专门匹配双大括号包裹的内容和双大括号之外的内容,就能准确区分静态和动态部分。

正则表达式说明

使用/({{([^}]+)}})|([^{]+)/g这个正则:

  • ({{([^}]+)}}):匹配被{{}}包裹的内容,捕获组2是括号内的动态值
  • ([^{]+):匹配非{开头的连续字符,也就是静态内容

改进后的代码

function templateParser(string) {
  const re = /({{([^}]+)}})|([^{]+)/g;
  const output = [];
  let match;

  while ((match = re.exec(string)) !== null) {
    // 匹配到动态内容(双大括号包裹)
    if (match[1]) {
      output.push({
        type: "dynamic",
        value: match[2]
      });
    } 
    // 匹配到静态内容
    else if (match[3]) {
      output.push({
        type: "static",
        value: match[3]
      });
    }
  }

  return output;
}

// 测试
console.log(templateParser("Lorem {{ipsum dolor sit}} amet, {consectetur} adipiscing {{elit}}."));

代码解释

  1. 正则会交替匹配动态的双大括号内容和静态的非{开头内容
  2. 通过判断捕获组是否存在,区分静态/动态项
  3. 动态值直接取双大括号内部的内容(捕获组2),静态值取捕获组3的内容
  4. 单个大括号包裹的内容会被识别为静态部分,完全符合示例需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:16:04