【问题标题】:How to find and replace every nth character occurrence using regex?如何使用正则表达式查找和替换每第 n 个字符出现?
【发布时间】:2021-03-14 16:09:19
【问题描述】:

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

similar question,但它每四个字符寻址一次,但我需要字符串中每个“nth”出现的特定字符。

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

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

但是如何为上述问题编写正则表达式?

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

我在 Sxundxaxs 上玩得不亦乐乎。

到:

我在 Sxundyaxs 上没有任何关系。

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

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    你可以使用:

    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

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2015-02-19
      • 2019-07-23
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多