osmiumbin
osmiumbin

Reputation: 339

Regex to replace every newline

I need to replace every newline character in a string with another character (say 'X'). I do not wish to collapse multiple newlines with a single newline!

PS: this regex replaces all consecutive newlines with a single newline but its not what I need.

Regex regex_newline = new Regex("(\r\n|\r|\n)+");

Upvotes: 4

Views: 17205

Answers (3)

3per
3per

Reputation: 384

Since .Net6 ReplaceLineEndings extensions method provides such ability.

string tmp = """
1
2
""";

Console.WiteLine(tmp.ReplaceLineEndings()); // replace line endings to  Environment.NewLine
Console.WiteLine(tmp.ReplaceLineEndings("<br/>")); // replace line endings to <br/>

Upvotes: 0

James Curran
James Curran

Reputation: 103485

That will replace one or more newlines with something, not necessarily with a single newline -- that's determined by the regex_newline.Replace(...) call, which you don't show.

So basically, the answer is

 Regex regex_newline = new Regex("(\r\n|\r|\n)");   // remove the '+'
 // :
 regex_newline.replace(somestring, "X");

Upvotes: 17

mboldt
mboldt

Reputation: 1825

Just use the String.Replace method and replace the Environment.NewLine in your string. No need for Regex.

http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

Upvotes: 8

Related Questions