|
|
Title | Replace unprintable characters with spaces in Visual Basic .NET |
Description | This example shows how to replace unprintable characters with spaces in Visual Basic .NET. |
Keywords | character, ASCII, replace, regular expressions, regex, VB.NET |
Categories | Miscellany, Strings, Algorithms |
|
|
Thanks to Gary Winey (j2associatesNO_SPAM@yahoo.com).
Gary provides this simple function for converting unprintable characters with ASCII codes between 0 and 31 into spaces. It builds a string containing the disallowed characters surrounded by square brackets. It then uses regular expressions to match any of those characters and replace them with spaces.
|
|
Private Function CleanseData(ByVal textToCleanse As String, _
_
Optional ByRef changeCount As Integer = 0) As String
' Create illegal character string
Dim badChars As String = String.Empty
For index As Integer = 0 To 31
' Use ChrW instead of Chr to avoid boxing
badChars &= ChrW(index)
Next
' Build RegEx pattern - square brackets say match any
' one of them
Dim pattern As String = "[" & badChars & "]"
' Are there any illegal characters
If Regex.IsMatch(textToCleanse, pattern) Then
' Count them
changeCount = Regex.Matches(textToCleanse, _
pattern).Count
' Convert them to spaces
textToCleanse = Regex.Replace(textToCleanse, _
pattern, " ")
End If
Return textToCleanse
End Function 'CleanseData
|
|
|
|
|
|