Thursday, December 13, 2007

Remove Duplicate Whitespaces using Regular Expressions

A quick way to eliminate duplicate white spaces from a string using regular expressions using VB.Net


Dim DirtySample As String = "The quick brown fox " & ControlChars.CrLf & " jumped" & ControlChars.Tab & ControlChars.Tab & " over lazy dog"
Dim CleanSample As String = System.Text.RegularExpressions.Regex.Replace(DirtySample, "\s+", " ")

Debug.WriteLine("DirtySample : ")
Debug.WriteLine(DirtySample)

Debug.WriteLine("CleanSample : ")
Debug.WriteLine(CleanSample)


Output

DirtySample :
The quick brown fox
 jumped over lazy dog
CleanSample :
The quick brown fox jumped over lazy dog

No comments: