javascript - 如何使用 JavaScript 解析带有双大括号的字符串?

标签 javascript regex

是否有快速的正则表达式方法或类似的方法可以将字符串解析为双花括号中的位(我们称它们为“静态”)和 在双花括号中(让我们称之为“动态”)?

例如输入:

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}}."
  )
);

最佳答案

区分{{ this }}that capture 的想法this匹配 that

{{(.*?)}}|.+?(?={{|$)

See this demo at regex101JS-demo at tio.run

使用 exec 您的值可以很容易地根据例如m[1]!=null(第一组匹配)。当然这与你的示例数据有关。假设没有嵌套并且没有猜测任何其他内容。

关于javascript - 如何使用 JavaScript 解析带有双大括号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73026239/

相关文章:

Python 正则表达式 : Capture lookahead value (capturing text without consuming it)

Python 3.5.1 re.sub 不适用于多行

javascript - 如何将此字符串转换为 javascript Date 对象?

javascript - 清除Select2的所有列表项而不是选定的

javascript - 在 ajax :beforeSend (link_to)? 中添加额外数据

c# - 将斜杠添加到自关闭标签

javascript - 在键入 bootstrap select jquery 时加载选择选项

javascript - 嵌套执行流程控制

php - str_replace : Match whole word only

php - preg_match 不接受新行