Xedicon
Xedicon

Reputation: 128

How to remove characters from a string in VBscript

I'm new to vbscript and Stack Overflow, and could really use some help.

Currently I'm trying to format a phone number that is read from an image and stored in a variable. Because the images are "dirty" extra characters find their way in, such as periods or parenthesis. I've already restricted the field as much as possible to help prevent picking up extra characters, but alas!

For example I want to turn ",123.4567890" into "123 456 7890" (not including the double quotes). Trouble is I won't know what extra characters could potentially be picked up, ruling out a simple replace.

My logic is remove any non numeric characters, start from the left, insert a space after the third number, insert a space after the sixth number.

Any help would be great, and please feel free to ask for more information if needed.

Upvotes: 5

Views: 26360

Answers (2)

Kul-Tigin
Kul-Tigin

Reputation: 16950

Welcome to Stack Overflow. You can remove non-digits using Regex, and concatenate the parts using Mid function.

For example:

Dim sTest
sTest = ",123.4567890"

With (New RegExp)
    .Global = True
    .Pattern = "\D" 'matches all non-digits
    sTest = .Replace(sTest, "") 'all non-digits removed
End With

WScript.Echo Mid(sTest, 1, 3) & " "& Mid(sTest, 4, 3) & " "& Mid(sTest, 7, 4)

Or fully using Regex (via a second grouping pattern):

Dim sTest
sTest = ",123.4567890"

With (New RegExp)
    .Global = True
    .Pattern = "\D" 'matches all non-digits
    sTest = .Replace(sTest, "") 'all non-digits removed
    .Pattern = "(.{3})(.{3})(.{4})" 'grouping
    sTest = .Replace(sTest, "$1 $2 $3") 'formatted 
End With

WScript.Echo sTest

Upvotes: 4

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Use a first RegExp to clean non-digits from the input and second one using groups for the layout:

Function cleanPhoneNumber( sSrc )
  Dim reDigit : Set reDigit = New RegExp
  reDigit.Global  = True
  reDigit.Pattern = "\D"
  Dim reStruct : Set reStruct = New RegExp
  reStruct.Pattern = "(.{3})(.{3})(.+)"
  cleanPhoneNumber = reStruct.Replace( reDigit.Replace( sSrc, "" ), "$1 $2 $3" )
End Function ' cleanPhoneNumber

Upvotes: 1

Related Questions