首页 > 解决方案 > 无法使用 RegExp 替换

问题描述

我正在尝试使用 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 #

标签: javascriptregexstringreplaceregexp-replace

解决方案


如果这是你去的:

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

推荐阅读