Regex will replace all occurrences

I need to replace a string where it follows a specific string and some variable data. I need to keep the beginning and middle and just replace the end. When I tried the code below, it only replaces the last event. I tried to switch to a non-greedy match, but then he won’t find it. The middle can contain new lines, as well as 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 to replace each event "Old End".

+7
source share
2 answers

I think Kendall hits the linked link, not a greedy match , for example.

 s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*?) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase); 

Gotta do the trick.

Edit:

You should also be able to modify the template inside the capture area:. .* Where . will match any character except the newline character.

+6
source

If all you want to do is replace Old ending with New ending , why don't you just use the good old string.Replace ? It will be simpler and faster than using regex

 String s = "Beginning of story. Keep this sentence. Old ending.\n"; s.Replace("Old ending", "New ending"); 

Update: To replace Old ending , where it is preceded by Begining of story... , use this regular expression (?<=Beginning of story.*?)Old ending , play with it if you have small changes, but this should lead you there

 Regex.Replace(s, @"(?<=Beginning of story.*?)Old ending", "New ending"); 

It basically says, find and replace “Old End” with “New Finale”, but only if it starts with “Begin Blah Blah Blah History”

+6
source

All Articles