How can you replace all non numeric characters in a string with " " (space)
Anyone know what the fastest way would be to do this?
Re: How can you replace all non numeric characters in a string with " " (space)
Like with virtually everything, which method is fastest depends on the circumstances - in this case including things like the length of the string, how many are likely to be numeric, the possible non-numeric characters, and the source of the string.
As a generic method, this should be fairly fast:
Code:
Dim strOutput as String
Dim lngChar as Long
strOutput = Space(Len(strInput))
For lngChar = 1 To Len(strInput)
Select Case Mid$(strInput,lngChar,1)
Case "0" to "9"
Mid$(strOutput,lngChar,1) = Mid$(strInput,lngChar,1)
End Select
Next lngChar
Re: How can you replace all non numeric characters in a string with " " (space)
This function will also work well.
Code:
Sub test()
Dim st As String: st = "zero_0_one=1=two~2~three'3'four#4#five"
Debug.Print ReplaceAll(st)
End Sub
Code:
Function ReplaceAll(ByVal strText As String) As String
Dim RegExp As Object
Set RegExp = CreateObject("VBScript.RegExp")
With RegExp
.Pattern = "([^0-9])"
.Global = True
.IgnoreCase = False
.MultiLine = True
ReplaceAll = .Replace(strText, " ") ' " $1"
End With
End Function