Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleReplace unprintable characters with spaces in Visual Basic .NET
DescriptionThis example shows how to replace unprintable characters with spaces in Visual Basic .NET.
Keywordscharacter, ASCII, replace, regular expressions, regex, VB.NET
CategoriesMiscellany, 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
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated