有没有快速正则表达式方法或类似方法可以将字符串解析为双花括号中的not位(我们称之为"静态")和双花括号中的are位(我们称之为"动态")?

例如,输入:

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: "."
  },
]

到目前为止,我最好的try 是使用/\{*([^{}]+)\}*/g作为正则表达式,并使用whileexec循环,但它错误地将any个花括号标识为动态值,如下所示:

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区分为一个 idea 、capturethismatchthat.

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

JS-demo at tio.run.com/r/lsIkEo/1" rel="nofollow noreferrer">See this demo at regexJS-demo at tio.runJS-demo at tio.run

使用exec可以很容易地根据m[1]!=null(first group匹配)设置值.当然,这与您的样本数据有关.假设没有筑巢,也没有猜测其他任何东西.

Javascript相关问答推荐

我无法使用tailwind-css和reactJS修改图像的位置

如何在ReactJS中修复这种不需要的按钮行为?

除了在Angular 16中使用快照之外,什么是可行且更灵活的替代方案?

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

使用TMS Web Core中的HTML模板中的参数调用过程

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

我试图实现用户验证的reduxstore 和操作中出了什么问题?

单击更新页面的按钮后,页面刷新;测试/断言超时,有两个标题,但没有一个标题

从mat—country—select获取整个Country数组

角色 map 集/spritebook动画,用户输入不停止在键上相位器3

在vercel throws上部署带有gunjs的sveltekit应用无法找到模块./' lib/文本编码'

仅针对RTK查询中的未经授权的错误取消maxRetries

使用useEffect,axios和useParams进行react测试

Chart.js 4.4.2,当悬停在一个数据点上时,如何在工具提示中拥有多个数据点/标签?

显示图—如何在图例项上添加删除线效果?

Ember.js 5.4更新会话存储时如何更新组件变量

我怎么在JS里连续加2个骰子的和呢?

在Java中寻找三次Bezier曲线上的点及其Angular

如何使用JS创建一个明暗功能按钮?

有效路径同时显示有效路径组件和不存在的路径组件