Click to See Complete Forum and Search --> : s/(// not working
MacPC
11-01-2008, 08:55 AM
Hi, I have a form that allows user input phone number. But if a user enter the number in this format (888) 555-5555, the variable $phone_num will be like this $phone_num = (888) 555-5555. However, I need to find a way to trim out the ( ) the space and the -, it's easy to do this in php, but how can I do that in Perl?
I tried using $phone_num =~s/(//g; But everytime I did that I got no respones. Any helps will be greatly appreciated.
MacPC
11-01-2008, 09:26 AM
Hi,
I just by chance found something like this
$phone =~ s/[\/ (\[\]\)\-&\t]//g;
And this works just the way I want it. but I don't understand how this works, could some one be kind enough to explain it to me?
Nedals
11-01-2008, 03:40 PM
[\/ (\[\])\-&\t] defines a set of chars, using [....], to be replaced with nothing (deleted)
The '\' is used to escape special chars.
A much easier way would be to delete all non-digits.
$phone =~ s/\D//g;
MacPC
11-01-2008, 10:02 PM
Hi Nedals,
Thanks you so much. So basically it is like this
In this:
s/[\/ (\[\]\)\-&\t]//g;
[ opening bracket
\/ meaning esp /
what about the blank space? no \ esp needed?
what about the ( ? o \ esp needed?
\[ meaning esp [
\] meaning esp ]...
then what is the &
and the \t?
] close bracket
then replace everything with nothing.
I hope this make sense cuz I what to \u\n\d\e\r\s\t\a\n\d \i\t \c\o\r\r\e\c\t\l\y. \:\)
I like this $phone =~ s/\D//g; :)
Sixtease
11-02-2008, 09:50 AM
& means literal '&' and \t means tab. :-)
You may find perldoc perlreref (http://search.cpan.org/~rgarcia/perl-5.10.0/pod/perlreref.pod#ESCAPE_SEQUENCES) helpful.
Nedals
11-02-2008, 02:04 PM
Think about it this way.
In this regex, somewhat more complex than you need, you will remove...
'/ space ( [ ] ) - & tab' -BUT- '/ ( [ ] ) -' have special meaning in a reqex function so they must be escaped with \
space can be literal, as here, or you can use \s
tab, as Sixtease said, is represented by \t
One thing that supprised me was that the '(' was not escaped, but it still worked.
In your case, the regex could have been written...
$phone =~ s/[\(\)\-\s]//g;
-or-
$phone =~ s/(\(|\)|\-|\s)//g; meaning '( or ) or - or \s' where 'or' is replaced by '|' enclose with (...)
This is useful when you want to remove character groups instead of single chars.
-or-
$phone =~ s/\D//g; :)
Jeff Mott
11-02-2008, 04:17 PM
Wow... these regexs are getting far more complicated than they need be.
First, MacPC, the only problem with what you originally posted is that "(" is a special character in regular expressions, so you need to prefix it with a backslash.
$phone_num =~ s/\(//g;
That being said, Nedals' solution is better. It removes all parentheses, spaces and hyphens in one fell swoop.
$phone_num =~ s/\D//g;
MacPC
11-02-2008, 05:00 PM
Thank you everyone so very much and thank you Nedals for such a good explaination. It all makes so much more sense now. :)
\L\o\v\e\ \t\h\i\s\ \f\o\r\u\m