【问题标题】:How to replace a number within a string by itself + 1?如何用自身+ 1替换字符串中的数字?
【发布时间】:2020-04-01 16:26:29
【问题描述】:

我有一个字符串,如 “我们有一个 foobar,每个 bar 最多可以提供 20 个 foo。” 我想替换每次出现的 “最多” em> + 带有<number++ 的任意长度的数字。上述字符串将导致:

“我们有一个 foobar,每个 bar 可以提供

我坚持了这样的事情:

string.replace("/maximum\sof\s\d+/ig", `<${$1++}`)

但我不能让它作为 $1 仅反向引用整个捕获组而不是单个数字。我也对字符串格式感到困惑。

【问题讨论】:

    标签: javascript regex replace backreference


    【解决方案1】:

    你可以使用回调函数和捕获组

    maximum\sof\s(\d+)
    
    • maximum\sof\s - 匹配 maximum of
    • (\d+) - 匹配一个或多个数字(捕获组 1)

    在回调中,我们可以使用捕获的组来替换我们想要的任何额外内容

    let str = "We have a foobar which can provide a maximum of 20 foo per bar."
    let replaced = str.replace(/maximum\sof\s(\d+)/ig, (_, g1) => '<' + (+g1+1))
    
    console.log(replaced)

    【讨论】:

      【解决方案2】:

      替换可以使用一个函数:

      let input = "We have a foobar which can provide a maximum of 20 foo per bar.";
      
      console.log(
        input.replace(/(?:\ba )?maximum of ([0-9]+)\b/, function (all, max) {
          return "<" + (max / 1 + 1);
        })
      );

      这匹配/(?:\ba )?maximum of ([0-9]+)\b/(带有可选的前导分词和),然后对结果运行一个函数:整个匹配(我们不使用),然后是数字。然后我们可以将该段与修改后的数字缝合在一起。我除以 1 是为了确保 max 被视为一个数字(否则它会是一个字符串,因此连接到 201 而不是 21)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 2015-12-25
        • 2013-05-03
        相关资源
        最近更新 更多