Results 1 to 3 of 3

Thread: How can you replace all non numeric characters in a string with " " (space)

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2003
    Posts
    1,269

    How can you replace all non numeric characters in a string with " " (space)

    Anyone know what the fastest way would be to do this?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    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

  3. #3
    Lively Member
    Join Date
    Dec 2007
    Posts
    76

    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
    Last edited by klen_; Nov 14th, 2009 at 01:52 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width