Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Combining two actions in RegExp

by Anonymous Monk
on Jan 23, 2018 at 20:01 UTC ( [id://1207775]=note: print w/replies, xml ) Need Help??


in reply to Re: Combining two actions in RegExp
in thread Combining two actions in RegExp

That works, can spaces be removed from the string if found using TR?
e.g. my $phone = "(xxx) 1234-0000";

Replies are listed 'Best First'.
Re^3: Combining two actions in RegExp
by Cristoforo (Curate) on Jan 23, 2018 at 20:31 UTC
    $phone =~ tr/)(/-/d; says to delete the parentheses and also replace the closing paren with '-';

    To also delete any spaces, you could use $phone =~ tr/)(\x20/-/d; where '\x20' is the hex value of a 'space'. You could also use $phone =~ tr/)( /-/d; without the hex value of a space and just use a literal space instead. (The hex version just makes the 'space' more explicit).

      Hi, in a situation where the string looks like this one:

       my $phone = "(777) 1234-0000 RAM:007";

      How would remove just the space after the "(777) "?
      The end result would be like:  777-1234-0000 RAM:007

      Thank you!

        One way:

        c:\@Work\Perl\monks>perl -wMstrict -le "my $phone = '(777) 1234-0000 RAM:007'; print qq{'$phone'}; ;; my %xlate = ( '(' => '', ') ' => '-' ); ;; $phone =~ s{ ([()][ ]?) }{$xlate{$1}}xmsg; print qq{'$phone'}; " '(777) 1234-0000 RAM:007' '777-1234-0000 RAM:007'

        Update 1: I know, I know, the next thing you're going to ask is "how do I handle any number of spaces after the closing paren?"

        c:\@Work\Perl\monks>perl -wMstrict -le "my @phones = ( '(777)1234-0000 RAM:007', '(777) 1234-0000 RAM:007', '(777) 1234-0000 RAM:007', '(777) 1234-0000 RAM:007', ); ;; my %xlate = ( '(' => '', ')' => '-' ); ;; for my $phone (@phones) { printf qq{'$phone' -> }; ;; $phone =~ s{ ([()]) \s* }{$xlate{$1}}xmsg; print qq{'$phone'}; } " '(777)1234-0000 RAM:007' -> '777-1234-0000 RAM:007' '(777) 1234-0000 RAM:007' -> '777-1234-0000 RAM:007' '(777) 1234-0000 RAM:007' -> '777-1234-0000 RAM:007' '(777) 1234-0000 RAM:007' -> '777-1234-0000 RAM:007'

        Update 2: Another version of the substitution that does not depend on a translation table and is more flexible WRT area code format:
            $phone =~ s{ \( \s* (\d{3}) \s* \) \s* }{$1-}xmsg;


        Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1207775]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-24 03:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found