[RESOLVED] Need help with removing multiple carriage returns
Hello, I'm trying to remove multiple carriage returns and linefeeds from a string. However my code can't do this, unlikely it could, in my other application. Here's my code:
Code:
str = str.Replace(ControlChars.Lf, ControlChars.NewLine)
str = str.Replace(ControlChars.Cr, ControlChars.NewLine)
str = str.Replace(ControlChars.CrLf, ControlChars.NewLine)
str = str.Replace(ControlChars.NewLine & ControlChars.NewLine & ControlChars.NewLine, ControlChars.NewLine)
str = str.Replace(ControlChars.NewLine & ControlChars.NewLine, ControlChars.NewLine)
Re: Need help with removing multiple carriage returns
Here's my example. I'm not 100% sure what a carriage return is or newline feed I just took a guess.
Code:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "This is a cool \n line feed and carriage \r returnerd that returns my \r bone"
Console.WriteLine(RemoveExcess(str))
Console.ReadLine()
End Sub
Private Function RemoveExcess(input As String) As String
Return Regex.Replace(input, "\\r|\\n", String.Empty)
End Function
End Module
Re: Need help with removing multiple carriage returns
You can do this with regex
Code:
Sub Main()
Dim sample = <sample>
this
is
a bunch
of text
neat!
</sample>
Dim rx = New System.Text.RegularExpressions.Regex("[\r\n]+")
Dim cleanString = rx.Replace(sample.Value, Environment.NewLine)
Console.WriteLine(cleanString)
End Sub
Re: Need help with removing multiple carriage returns
Quote:
Originally Posted by
wild_bill
-
I beat you again to the Regex war :p. This time by 3 minutes.
Re: Need help with removing multiple carriage returns
Quote:
Originally Posted by
nikel
Hello, I'm trying to remove multiple carriage returns and linefeeds from a string. However my code can't do this, unlikely it could, in my other application. Here's my code:
Code:
str = str.Replace(ControlChars.Lf, ControlChars.NewLine)
str = str.Replace(ControlChars.Cr, ControlChars.NewLine)
str = str.Replace(ControlChars.CrLf, ControlChars.NewLine)
str = str.Replace(ControlChars.NewLine & ControlChars.NewLine & ControlChars.NewLine, ControlChars.NewLine)
str = str.Replace(ControlChars.NewLine & ControlChars.NewLine, ControlChars.NewLine)
Are you trying to replace multiple CR / LF with a single NewLine or replace all CR / LF with some other char?
This will replace multiples with a single:
Code:
Dim Sentence As String
Sentence = "Line1" & ControlChars.Lf & Environment.NewLine & ControlChars.CrLf & ControlChars.Cr & "line2"
Debug.WriteLine(Sentence)
Sentence = String.Join(Environment.NewLine, Sentence.Split(New Char() {ControlChars.Lf, ControlChars.Cr}, StringSplitOptions.RemoveEmptyEntries))
Debug.WriteLine("")
Debug.WriteLine(Sentence)
Re: Need help with removing multiple carriage returns
Thanks for all replies. dbasnett: Your code works fine. But why the others doesn't?