Find and replace every 3rd character occurrence in a given string and replace it with H
For instance : 74Mercedes1980 should be 74HerHedHs1H80
Can be done in C# or regex.
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');
console.log(str);
//=> I amx nexver ayt hoxme on Sxundyaxs
CodePudding user response:
The hard coded example equates to
var re = new Regex("((?:[^x]*x){2}[^x]*)x");
var result = re.Replace("I amx nexver axt hoxme on Sxundxaxs", m => m.Groups[1] "y");
Which can be rewritten as
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, m => m.Groups[1] "y");
Console.WriteLine(result);
Live example: https://dotnetfiddle.net/u8mJrn
CodePudding user response:
You can capture 2 non whitespace chars \S
and match the 3rd non whitespace char.
In the replacement use the capture group followed by the character that you want in the replacement.
If you want to also match a space, you can use a dot .
instead of \S
let str = '74Mercedes1980';
let n = 3;
let ch = 'H';
let regex = new RegExp("(\\S{" (n - 1) "})\\S", "g");
str = str.replace(regex, `$1${ch}`);
console.log(str);
In C# you can write this as
var str = "74Mercedes1980";
var n = 3;
var ch = 'H';
var regex = new Regex("(\\S{" (n - 1) "})\\S");
str = regex.Replace(str, "$1" ch);
Console.WriteLine(str);
Output
74HerHedHs1H80
See a C# demo