【问题标题】:How to split string into parts using Regex如何使用正则表达式将字符串拆分为多个部分
【发布时间】:2022-11-12 21:27:24
【问题描述】:

我有一个包含占位符的字符串,我想用其他字符串替换它,但我也想在遇到占位符时拆分该字符串。

所以,通过分裂我的意思是

"This {0} is an example {1} with a placeholder"

应该变成:

parts[0] -> "This"
parts[1] -> "{0}"
parts[2] -> "is an example"
parts[3] -> "{1}"
parts[4] -> "with a placeholder"

然后下一步是替换占位符(这部分很简单):

parts[0] -> "This"
parts[1] -> value[0]
parts[2] -> "is an example"
parts[3] -> value[1]
parts[4] -> "with a placeholder"

我知道如何匹配和替换占位符(例如({\d+})),但不知道如何告诉正则表达式同时“匹配非占位符”和“匹配占位符”。

我的想法是这样的:(?!{\d+})+ | ({\d+}) 但它不起作用。如果 Regex 风格很重要,我会在 JavaScript 中执行此操作。

如果我也可以一步用一个值替换占位符,那会很整洁,但我也可以在拆分后执行此操作。

【问题讨论】:

    标签: regex split match


    【解决方案1】:

    您可以将模式编写为:

    {d+}|S.*?(?=s*{d+}|$)
    

    Regex demo

    要获取具有这些值的数组:

    const regex = /{d+}|S.*?(?=s*{d+}|$)/gm;
    const str = `This {0} is an example {1} with a placeholder`;
    console.log(str.match(regex))

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 2013-09-11
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多