5

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.