Replace everything except numbers in a string vb6

2019-07-13 11:44发布

问题:

well i did my research and seen a lot of posts about this but couldnt find a solution in VB6 so how can i do this in VB6?

lets say i got a string like:

" Once upon a time there was a little kid who wonders about going further than 1000 of miles away from home... "

i want to get only numbers "1000" in this string seperated from string and wanna replace the whole string but numbers should stand still.

回答1:

The simplest way is to walk the string and copy numbers to a new one:

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

The result:

?GetNumbers("abc12def345")
12345

This is inefficient with long strings when there are lots of numbers though.



回答2:

Building on Deanna's answer:

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

This function should be O(n)

?GetNumbers("abc12def345")
12345


回答3:

You may use regular expressions:

Dim NumExp As New RegExp

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

strOutput = NumExp.Replace(strWhatToReplace, strReplaceWithWhat)


回答4:

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