How to find and replace every nth character occurrence using C# or regex? Conversion from Javascript to C#

Alice 71 Reputation points

I need to Find and replace every 3rd character occurrence in a given string and replace it with H.
Can be done in C# or Regex or any other.

I found this Javascript code that does the same thing and would like to convert it into a C# code. Can you please assist ?

Found here

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');  
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');  
//=> I amx nexver ayt hoxme on Sxundyaxs  
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,938 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 24,266 Reputation points Microsoft Vendor

    @Alice , Welcome to Microsoft Q&A, you could try the following link to convert the Javascript to c#.

         var ch = 'x';  
        var n = 3;  
        var str = "I amx nexver axt hoxme on Sxundxaxs";  
        var re = new Regex("((?:[^" + ch + "]*" + ch + "){" + (n - 1) + "}[^" + ch + "]*)" + ch);  
        var result = re.Replace(str, "${1}y");  

    Tested result:


    Hope this could help you.

    Best Regards,

    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Rijwan Ansari 741 Reputation points MVP

    HI @Alice

    You can try below code to get your desire result.

    var stringToApply = "74Mercedes1980";  
    var nth = 3;  
    var charToReplace = 'H';  
    var regex = new Regex("(\\S{" + (nth - 1) + "})\\S");  
    var outstr = regex.Replace(stringToApply, "$1" + charToReplace);  
    //output: 74HerHedHs1H80  

    0 comments No comments