如何使用正则表达式查找和替换字符串中每三次出现的“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
关于javascript - 如何使用正则表达式查找和替换第 n 个字符出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51097042/