Welcome to WebmasterWorld Guest from 54.205.96.97

Forum Moderators: ocean10000

Regex help

   
3:50 pm on Aug 24, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have the following code:


comments = "Please call (508) 241 5555 so we can discuss further"

Set objRegEx = CreateObject("VBScript.RegExp")

objRegEx.Global = True
objRegEx.Pattern = "^\D*(1)?\D*([1-9]\d{2})\D*(\d{3})\D*(\d{4})\D*$"

strNewString = objRegEx.Replace(comments, "($2) xxx-xxxx")

response.write strNewString


Right now the output is "(508) xxx-xxxx"

How can I make it so it is "Please call (508) xxx-xxxx so we can discuss further"

Thanks in advance
9:29 pm on Aug 24, 2013 (gmt 0)

WebmasterWorld Senior Member lucy24 is a WebmasterWorld Top Contributor of All Time Top Contributors Of The Month



Which part of the string is variable? The complete phone number, only the part after the area code-- or only the part other than the phone number?

Exact wording depends on the RegEx engine, but the basics will look something like this:

pattern = (\(\d\d\d\)\D*\d\d\d\D*\d\d\d\d)\b
output = oldstring.replace(pattern, "Please call $1 so we can discuss further")

objRegEx.Pattern = "^\D*(1)?\D*([1-9]\d{2})\D*(\d{3})\D*(\d{4})\D*$"

This seems needlessly complicated. At a minimum,
\d\d
is going to be simpler and faster than
\d{2}
Save the numbers in braces for times when you're capturing several iterations of a long pattern in parentheses.

Start by laying out in English all the possible forms your captured text can have. Are you looking strictly at phone numbers in North America, or also at other forms?

(\(\d+\)(?:\D?\d+)+)

for anything that starts with one or more numerals in parentheses.

But in practice you will need to replace \D with a group of only those characters that can actually occur in mid-phone number, such as [ /()-]. If a letter pops up in the middle of your string, you're no longer in a phone number so something has gone wrong. What if you've got two phone numbers in the same paragraph? A RegEx using only \D would capture from the beginning of one to the end of the next.
5:05 pm on Aug 25, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks Lucy

I did the following and it worked:

objRegEx.Pattern = "(\d{3})\D*(\d{4})\D*"
strNewString = objRegEx.Replace(comments, "xxx-xxxx")
5:52 pm on Aug 25, 2013 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Correction:

objRegEx.Pattern = "(\d{3})\D*(\d{4})"
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month