4

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! :)

Stefan
  • 5,644
  • 4
  • 24
  • 31

4 Answers4

5

\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)

Erik A. Brandstadmoen
  • 10,430
  • 2
  • 37
  • 55
0

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

Jonatas
  • 88
  • 1
  • 8
0

Try this (code not tested) -

formatedString  = Regex.Replace(text, "\r\n", "[Exp 1]", RegexOptions.Multiline)
ipr101
  • 24,096
  • 8
  • 59
  • 61
0

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   ")
Jochen
  • 380
  • 1
  • 3
  • 9