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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With