http://qs321.pair.com?node_id=1207776


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

$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).

Replies are listed 'Best First'.
Re^4: Combining two actions in RegExp
by Anonymous Monk on Jan 23, 2018 at 21:00 UTC
    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:  <%-{-{-{-<

        They all worked!
        my %xlate = ( '(' => '', ') ' => '-' ); $phone =~ s{ ([()][ ]?) }{$xlate{$1}}xmsg; # OR $phone =~ s{ \( \s* (\d{3}) \s* \) \s* }{$1-}xmsg;
        I need to go back and read on these lines of code, very clever, thank you very much!!