I need to replace a string where it follows a specific string and some varying data. I need to keep the beginning and the middle and just replace the end. When I tried the code below, it replaces only the last occurance. I have tried switching to a non greedy match but then it doesn't find it. The middle could contain new lines as well spaces, letters and numbers.
String s = "Beginning of story. Keep this sentence. Old ending.\n";
s += s;
s += s;
s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);
The result is this:
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. New ending.
How do I replace every occurance of "Old ending."
I think Kendall is bang on with the related link, a non greedy match e.g.
s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*?) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);
Should do the trick.
Edit:
You should also be able to change the pattern inside your capture region to be: .*
where .
will match any character except the newline character.
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