Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace all occurrences [duplicate]

Tags:

c#

.net

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."

like image 547
BrianK Avatar asked Jun 21 '13 18:06

BrianK


1 Answers

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.

like image 189
Chris Avatar answered Oct 21 '22 01:10

Chris