【问题标题】:Unable to replace using RegExp无法使用 RegExp 替换
【发布时间】:2021-02-12 14:38:48
【问题描述】:

我正在尝试使用 RegExp 替换一组特定的字符串,但它没有替换。我正在尝试的正则表达式是

\@223(?:\D|'')\gm

要测试的字符串集是这些

@223 ->Replace 223 with #
@223+@33 ->Replace 223 with #
@22;    ->Not Replace
@2234   ->Not Replace 
@22234  ->Not Replace
@223@44  ->Replace 223 with #

【问题讨论】:

  • 如果它以@223开头,您是否将其更改为223 with #
  • 你想用#替换233吗?
  • 只要使用str = str.replace(/@223\b/, "#")

标签: javascript regex string replace regexp-replace


【解决方案1】:

您的正则表达式有两个问题:

  1. 你使用了错误的斜线,应该是/@223(?:\D|'')/gm
  2. 非捕获组仍将包含在完整匹配中,因此您可能需要在 @223 部分周围添加括号并替换该组。

您可以在regex101.com 等服务中测试您的正则表达式。请注意,在该服务中,开始和结束斜线已经隐式包含在内。

【讨论】:

    【解决方案2】:

    如果你这样做了:

    var string = `
    @223
    @223+@33
    @22;
    @2234
    @22234
    @223@44
    `;
    regex = /(?<=@)(223)(?=\D)/g;
    string = string.replace(regex, "#");
    console.log(string);
    

    输出:

    @#
    @#+@33
    @22;
    @2234
    @22234
    @#@44
    

    解释:

    (?<=@) : test if leaded by @ character.
    (?=\D) : followed by any character except digit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多