Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a text by incrementing each occurence

I have a text say:

Hello
abc
Hello
def
Hello

I want to convert it to

Hello1
abc
Hello2
abc
Hello3

i.e I need to append a number after each occurrence of "Hello" text.

Currently I have 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 Replace method above used is:

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 is not working and is replacing the text in between.

Can you help me fixing that?

like image 727
Raghav Avatar asked Nov 24 '16 10:11

Raghav


1 Answers

Assuming Hello is just a placeholder for a more complex pattern, here is a simple fix: use a match evaluator inside Regex.Replace where you may 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 the C# demo

like image 157
Wiktor Stribiżew Avatar answered Nov 17 '22 20:11

Wiktor Stribiżew