Stefan
Stefan

Reputation: 5662

Replace line breaks using Regex

How can I replace all types of line breaks (CR, LF and CrLf) using Regex?

I´ve tried different combinations of "\n" and "\r" but none finds them all.

formatedString = System.Text.RegularExpressions.Regex.Replace(text, "\r\n", "[Exp 1]")

The following code does the job but it bugs me that I can´t seem to replace the Line Feed using Regexp.

formatedString = formatedString.Replace(Environment.NewLine, "[Environment.NewLine]") ' Equals CR
formatedString = formatedString.Replace(ControlChars.CrLf, "[ControlChars.CrLf]") ' CR and LF
formatedString = formatedString.Replace(ControlChars.Cr, "[ControlChars.Cr]") ' Carriage Return (CR)
formatedString = formatedString.Replace(ControlChars.Lf, "[ControlChars.Lf]") ' Line Feed (LF)

All advices are most welcome! :)

Upvotes: 4

Views: 16192

Answers (4)

Jochen
Jochen

Reputation: 420

The sample from @ipr101 takes 90%. But in case of CrLf, it creates 2 x " " instead of 1 x " ". Therefore, I'd recommend following script:

Dim source = String.Concat("Some string", vbLf, "with", vbCr, "line", vbCrLf, "breaks")
Dim result = Regex.Replace(source, "(?:\r\n|\r|\n)", " ")

If you like to preserve the line breaks and just add a prefix of space chars to each line, you can also use:

Dim source = String.Concat("Some string", vbLf, "with", vbCr, "line", vbCrLf, "breaks")
Dim result = Regex.Replace(source, "(?:\r\n|\r|\n)", "$0   ")

Upvotes: 0

Jonatas
Jonatas

Reputation: 108

Tested and working:

dim source = String.Concat("Some string", VbLf, "with", VbCr, "line", VbCrLf, "breaks")
dim result = Regex.Replace(source, "[\r\n]", " ")

https://dotnetfiddle.net/BcMbhZ

Upvotes: 0

ipr101
ipr101

Reputation: 24236

Try this (code not tested) -

formatedString  = Regex.Replace(text, "\r\n", "[Exp 1]", RegexOptions.Multiline)

Upvotes: 0

Erik A. Brandstadmoen
Erik A. Brandstadmoen

Reputation: 10588

\r, \n and \r\n should cover all cases of linebreaks. \n\r is not used by any system (that I know of...)

In VB, if not using regexes, you could replace all:

VbCr
VbLf
VbCrLf

with whatever line ending you prefer (obviously you can omit the preferred one from the list of "newline/cr" characters you replace)

Upvotes: 5

Related Questions