【问题标题】:How do I exclude a matched digit using regex?如何使用正则表达式排除匹配的数字?
【发布时间】:2021-06-03 12:14:35
【问题描述】:

给定字符串:the_number_10_is_important,我想捕获 _10_ 并排除 10

我基本上想用括号替换所有数字周围的下划线。

_\d+_ 选择_10_ 是我的出发点。我正在尝试使用lookaround 或非捕获组,例如。 _(?:\d+)_

【问题讨论】:

  • 看看这篇文章对你有没有帮助stackoverflow.com/questions/1395177/…
  • 你开始不错,但我猜你希望 \d+ 而不是 \d 来匹配多个数字
  • 为什么不简单:.replace(/_(\d+)_/g, "($1)")
  • 您必须使用捕获组并重复数字"the_number_10_is_important".replace(/_(\d+)_/g, "[$1]");
  • 感谢您的帮助。在这种情况下,替换 replace 中的括号似乎可以正常工作。

标签: javascript regex


【解决方案1】:

您需要捕获该数字并在替换时将其返回,因此您替换整个 _10_ 部分而不是仅替换下划线。

var s = "the_number_10_is_important";
var x = s.replace(/_(\d+)_/gm, "($1)");
console.log(x);

使用环视也可以按照自己的方式进行,但要复杂一些。

var s = "the_number_10_is_important";
var x = s.replace(/_(?=\d+)/gm, "(").replace(/(?<=\d+)_/gm, ")");
console.log(x);

【讨论】:

    【解决方案2】:

    然后结束这个,感谢The fourth bird

    您必须使用捕获组并重复数字"the_number_10_is_important".replace(/_(\d+)_/g, "[$1]");

    这是我自己的版本,但 sed 没有对 \d 的适当支持:

    sh$ echo "the_number_10_is_important_ but 10 should not be fooled by the real_0_ or the fake_1" | sed -E -e 's/_([0-9]+)_/[\1]/g'
    the_number[10]is_important_ but 10 should not be fooled by the real[0] or the fake_1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 2022-07-28
      • 1970-01-01
      相关资源
      最近更新 更多