替换字符串vb6中除数字之外的所有内容

时间:2011-12-21 12:20:02

标签: string vb6 replace

我做了我的研究并看过很多关于此的帖子,但无法在 VB6中找到解决方案 那我怎么能在 VB6

中做到这一点

假设我有一个字符串:

“曾几何时,有一个小孩想要离家远远超过1000英里......”

我想只从字符串中分离数字1000”并想要替换整个字符串,但数字应该保持不变。

4 个答案:

答案 0 :(得分:6)

最简单的方法是遍历字符串并将数字复制到新的数字:

Function GetNumbers(Value As String) As String
Dim Index As Long
Dim Final As String

  For Index = 1 To Len(Value)
    If Mid(Value, Index, 1) Like "[0-9]" Then
      Final = Final & Mid(Value, Index, 1)
    End If
  Next

  GetNumbers = Final
End Function

结果:

?GetNumbers("abc12def345")
12345

当有很多数字时,这对于长字符串效率很低。

答案 1 :(得分:2)

以迪安娜的回答为基础:

Function GetNumbers(Value As String) As String
Dim Index As Long
Dim Digit As String
Dim Final As String
Dim Count As Long

  Count = 1
  GetNumbers = Space(Len(Value))
  For Index = 1 To Len(Value)
    Digit = Mid(Value, Index, 1)
    If Digit Like "[0-9]" Then
      Mid(GetNumbers, Count, 1) = Digit
      Count = Count + 1
    End If
  Next

  GetNumbers = Left(GetNumbers, Count - 1)
End Function

此功能应为O(n)

?GetNumbers("abc12def345")
12345

答案 2 :(得分:0)

您可以使用正则表达式:

Dim NumExp As New RegExp

NumExp.Pattern = "\D"
NumExp.Global = True

strOutput = NumExp.Replace(strWhatToReplace, strReplaceWithWhat)

答案 3 :(得分:0)

nStr = "abc12def345"
For X = 1 To Len(nStr)
    If IsNumeric(Mid(nStr, X, 1)) = True Then
        nNum = nNum & Mid(nStr, X, 1)
    End If
Next X


MsgBox nNum