javascript - 如何使用正则表达式查找和替换第 n 个字符出现?

标签 javascript regex

如何使用正则表达式查找和替换字符串中每三次出现的“x”字符?

similar question但它处理每四个字符,但我需要字符串中特定字符的每“第 n 次”出现。

我正在使用 JavaScript replace() 方法,下面的示例会将每个 x 字符更改为 y:

replace(/\x/g, 'y')

但是我该如何为上面的问题编写正则表达式呢?

例如一些随机文本和预期结果:

I amx nexver axt hoxme on Sxundxaxs.

到:

I amx nexver ayt hoxme on Sxundyaxs.

我可以将 JS for 循环与 split()join() 一起使用,但使用 replace() 解决方案> 方法接缝更优雅。

最佳答案

您可以使用:

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');

因此,如果您每隔 3 次搜索一次,则在上述正则表达式的 {} 之间使用 n-1

要动态构建它,请使用:

let str = 'I amx nexver axt hoxme on Sxundxaxs';
let n = 3;
let ch = 'x';

let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");

str = str.replace(regex, '$1y');

console.log(str);
//=> I amx nexver ayt hoxme on Sxundyaxs

RegEx Demo

关于javascript - 如何使用正则表达式查找和替换第 n 个字符出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51097042/

相关文章:

java - 正则表达式用于匹配没有特定模式的数字

python - 正则表达式匹配每三位数字以逗号分隔的数字

javascript - Vue js - 找不到图像源时设置替代图像

javascript - Sharepoint 图像引用

javascript - PointClouds 和纹理的三个 js 透明度问题

regex - Jmeter - 嵌入变量和 $ 的正则表达式问题

c++ - regex_replace 问题

regex - 多行 sed 替换

javascript - Instruments Xcode 中的 UIAutomation 测试模块

javascript - {"errors": ["Invalid image URL"]} with aviary integration