Link to home
Start Free TrialLog in
Avatar of shawn857
shawn857

asked on

Doing a basic "search and replace" on phone numbers

Hi, back with another basic regex question. I know just the rudiments of regex "search", but nothing about the "replace" aspect of it. Looked at an online tutorial regarding it:

http://www.regular-expressions.info/replacetutorial.html

... but found it quite hard to follow - offering very few examples. What I want to do isn't very complicated - basically just a phone number extraction/modification. For example:

Here is my source text string:

Bob, Smith, 256-871-9082

My regex search statement is :  \d\d\d[\-]\d\d\d[\-]\d\d\d\d

After grabbing the matching phone number, I'd like to do a "replace" on the match to modify it to look like so:  

+1-(256)*8719*082

Any suggestions please, on the regex "replace" statement I would need?

Thanks
    Shawn
Avatar of ozo
ozo
Flag of United States of America image

#!/usr/bin/perl
$_='Bob, Smith, 256-871-9082';
s/(\d\d\d)-(\d\d\d)-(\d)(\d\d\d)/+1-($1)*$2$3*$4/;
print;
Avatar of shawn857
shawn857

ASKER

Thanks ozo... is there any way to do this without using capture groups?

Thanks
   Shawn
Yes, but not a simple way.
Oh, I see. Ozo, is the syntax used in the replace portion of a regex completely different than the syntax in the search portion?

Thanks
   Shawn
In the replace portion, meta-characters lose their meaning.
OK, so the only syntax you have to work with is () (capture groups) and $ (dollar sign)... basically?

Shawn
In perl, $ for scalar interpolation retains its meaning.  () for capture and $ for end of string lose their search meanings.
is that the only syntax used in replace?
In perl, the replacement is just a qquoted string.
Variables that happen to have certain values, like $1, $2, are interpolated like they would be in any other qquoted string.
(with the /e or /ee modifier, the string is also evaluated)
I don't know what you mean by interpolated Ozo. I'm not using Perl, I'm using a regex  engine for Delphi programming language.

Thanks
   Shawn
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Ozo.

Cheers
    Shawn