Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Xedicon Avatar asked Sep 21 '11 20:09

Xedicon


People also ask

How do I remove the first 3 characters from a string?

Use the String. substring() method to remove the first N characters from a string, e.g. const result = str. substring(N) . The substring method will return a new string that doesn't contain the first N characters of the original string.

What is the use of MID () function in VBScript?

The Mid function returns a specified number of characters from a string. Tip: Use the Len function to determine the number of characters in a string.

What is InStr function in VBScript?

The InStr Function returns the first occurrence of one string within another string. The search happens from left to right.


2 Answers

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
like image 60
Kul-Tigin Avatar answered Sep 22 '22 18:09

Kul-Tigin


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
like image 21
Ekkehard.Horner Avatar answered Sep 23 '22 18:09

Ekkehard.Horner