Reputation: 33
I'm trying to replace all occurences of a multiline string in another string. Assuming that input contains the input text, output contains the resulting text, searchText contains the multiline string to be found and replaceText contains the replaced multiline string, I used this code:
output = input.Replace(searchText, replaceText);
The problem is that it works only with single line strings (that don't include newlines). How could I make it work for strings that contain newlines?
e.g.
searchText = "ABC\nDEF";
replaceText = "text";
input:
ABC
DEF
KLF
Z
output:
text
KLF
Z
Upvotes: 0
Views: 1292
Reputation: 2305
You need to know what the new line is in the input. It could be LF only, but it could be CR+LF.
I am a little bit lazy to explain, so please read this Wikipedia about new line: https://en.wikipedia.org/wiki/Newline
So your problem might be because CR is also there, which makes that the string to search does not match at all. One solution is to set your search text as:
searchtext = "ABC" + System.Environment.NewLine + "DEF";
System.Environment.NewLine deals with the new line for you better. See the reference in msdn: https://msdn.microsoft.com/en-us/library/system.environment.newline(v=vs.110).aspx
Upvotes: 4