regex 如何替换分隔符之间的重复字符串?

jpfvwuh4  于 2023-08-08  发布在  其他
关注(0)|答案(3)|浏览(120)

我需要替换分隔符中的一个文本序列,精确地替换它出现的次数。例如,我有这样的文本:

"Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH too but it doesn't moo; bah!"

字符串
我想替换每一个“哞;“&”和“RGH”之间有一个“A”,所以我期望:

"Cow says &ARGH but also &AAARGH and &AAAAARGH but it doesn't moo; bah!"


换句话说,我必须替换每一个“哞;“&”和“RGH”之间的“A”。我必须通过JavaScript使用单个regexp在整个文本上替换它(如果可能的话)我做了很多尝试,例如:

var a="Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH but it doesn't moo; bah!"
a=a.replace(/(?<=&)((moo;)\1?)+RGH/g,"A");
// a=a.replace(/&(moo;)+RGH/g,"A")
// a=a.replace(/&(?=moo;)\1RGH/g,"A"
console.log(a);


但没有明显的成功。这个想法是,每一个“哞;必须用“A”替换,只有当与其他“moo”沿着出现时;“s在“&”和“RGH”之间
有什么建议吗?谢谢你,谢谢

xuo3flqw

xuo3flqw1#

您可以将(moo;)*放入lookbehind和lookahead判断提示中。这样,正则表达式将匹配&RGH之间的所有moo:

var a="Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH but it doesn't moo; bah!"
a=a.replace(/(?<=&(moo;)*)moo;(?=(moo;)*RGH)/g, 'A');
console.log(a);

字符串
基准测试:


的数据

<script benchmark data-count="1000000">

let a = "Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH too but it doesn't moo; bah!";

// @benchmark Unmitigated
a.replace(/(?<=&)(moo;)+(?=RGH)/g, m => 'A'.repeat(m.length / 4));

// @benchmark Alexander
a.replace(/(?<=&(moo;)*)(moo;)(?=(moo;)*RGH)/g, 'A');

</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

pw136qt2

pw136qt22#

您还可以匹配moo;的所有连续序列,并向String#replace传递一个回调函数,该回调函数根据每个序列的长度替换每个序列。

let str = "Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH too but it doesn't moo; bah!";
let res = str.replace(/(?<=&)(moo;)+(?=RGH)/g, m => 'A'.repeat(m.length / 4));
console.log(res);

字符串

irlmq6kh

irlmq6kh3#

因为你想替换每个出现的 “moo;“,您将只希望匹配单个出现,而不是一个序列。
您可以使用 look-around 语法来Assert “moo;“

(?<=&|moo;)moo;(?=RGH|moo;)

字符串

var string = 'Cow says &moo;RGH but also &moo;moo;moo;RGH and &moo;moo;moo;moo;moo;RGH too but it doesn\'t moo; bah!'
string = string.replace(/(?<=&|moo;)moo;(?=RGH|moo;)/g, 'A')

console.log(string)

相关问题