如何删除特定的特殊字符

时间:2013-06-28 20:25:09

标签: vb6

我有一个像X5BC8373XXX这样的字符串。其中X =特殊字符等于Square 我也有一些像\n这样的特殊字符,但我删除了它们,但是我无法移除方块...... 我想知道如何删除它。
我找到了这个方法:

Dim Test As String
Test = Replace(Mscomm1.Input, Chr(160), Chr(64) 'Here I remove some of the special characters like \n
Test = Left$(Test, Len(Test) -2)
Test = Right$(Test, Len(Test) -2)

此方法会移除这些特殊字符,但它也会移除我的第一个字符5 我意识到这种方法只会从leftright中删除2个字符 但我怎么能解决这个问题呢?

我也看到vblF, CtrlF这样的东西,但我无法解决这个问题; \

3 个答案:

答案 0 :(得分:4)

您可以使用正则表达式。如果要删除不是数字或字母的所有内容,可以使用下面的代码。如果您想要保留其他字符,正则表达式可以高度自定义,但可能会有点混乱。

这也有利于一次完成整个字符串,而不是逐个字符。

您需要在项目中引用 Microsoft VBScript正则表达式

Function AlphaNum(OldString As String)
   Dim RE As New RegExp
   RE.Pattern = "[^A-Za-z0-9]"
   RE.Global = True
   AlphaNum = RE.Replace(OldString, "")
End Function

答案 1 :(得分:3)

清除不可打印的字符非常简单。一种蛮力但易于定制的方法可能是:

Private Function Printable(ByVal Text As String) As String
    Dim I As Long
    Dim Char As String
    Dim Count As Long

    Printable = Text 'Allocate space, same width as original.
    For I = 1 To Len(Text)
        Char = Mid$(Text, I, 1)
        If Char Like "[ -~]" Then
            'Char was in the range " " through "~" so keep it.
            Count = Count + 1
            Mid$(Printable, Count, 1) = Char
        End If
    Next
    Printable = Left$(Printable, Count)
End Function

Private Sub Test()
    Dim S As String

    S = vbVerticalTab & "ABC" & vbFormFeed & vbBack
    Text1.Text = S 'Shows "boxes" or "?" depending on the font.
    Text2.Text = Printable(S)
End Sub

答案 2 :(得分:0)

这将删除控制字符(低于 CHR(32))

Function CleanString(strBefore As String) As String
  CleanString = ""
  Dim strAfter As String
  Dim intAscii As Integer
  Dim strTest As String
  Dim dblX As Double
  Dim dblLen As Double
  intLen = Len(strBefore)
  For dblX = 1 To dblLen
    strTest = Mid(strBefore, dblX, 1)
    If Asc(strTest) < 32 Then
      strTest = " "
    End If
    strAfter = strAfter & strTest
  Next dblX
  CleanString = strAfter
End Function