Replace text, increasing each lineage

I have a text:

Hello abc Hello def Hello 

I want to convert it to

 Hello1 abc Hello2 abc Hello3 

ie I need to add a number after each occurrence of the text "Hello".

I have currently written this code:

 var xx = File.ReadAllText("D:\\test.txt"); var regex = new Regex("Hello", RegexOptions.IgnoreCase); var matches = regex.Matches(xx); int i = 1; foreach (var match in matches.Cast<Match>()) { string yy = match.Value; xx = Replace(xx, match.Index, match.Length, match.Value + (i++)); } 

and the replacement method used above:

 public static string Replace(string s, int index, int length, string replacement) { var builder = new StringBuilder(); builder.Append(s.Substring(0, index)); builder.Append(replacement); builder.Append(s.Substring(index + length)); return builder.ToString(); } 

Currently, the above code does not work and replaces the text between them.

Can you help me fix this?

+5
source share
1 answer

Assuming Hello is just a placeholder for a more complex template, here is a simple fix: use the conformity evaluator inside Regex.Replace , where you can use variables:

 var s = "Hello\nabc\nHello\ndef\nHello"; var i = 0; var result = Regex.Replace( s, "Hello", m => string.Format("{0}{1}",m.Value,++i), RegexOptions.IgnoreCase); Console.WriteLine(result); 

See C # demo

+9
source

Source: https://habr.com/ru/post/1260269/


All Articles