Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Removing Special Characters

by Shaveta_Chawla (Sexton)
on Nov 01, 2011 at 07:36 UTC ( #935048=perlquestion: print w/replies, xml ) Need Help??

Shaveta_Chawla has asked for the wisdom of the Perl Monks concerning the following question:

How can i remove all the special characters from a string. Suppose the string is::

$str = per#lm-on%ks&perl$*wis(+dom)

Replies are listed 'Best First'.
Re: Removing Special Characters
by moritz (Cardinal) on Nov 01, 2011 at 08:03 UTC
      For a banker "%" might not be special. And we are not even touching the subject of Unicode.


      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Removing Special Characters
by dsheroh (Monsignor) on Nov 01, 2011 at 08:49 UTC
    Step 1: Define which characters you consider to be "special".

      Step 1 (alternate): Define the set of characters that are not "special".

      It may be simpler to define the characters you want to keep rather than the ones to exclude. See also the tr///dc solution above.

Re: Removing Special Characters
by MVS (Monk) on Nov 01, 2011 at 07:50 UTC

    One possibility would be to use a regular expression to remove the characters you don't want:

    $str =~ s/[#\-%&\$*+()]//g;

    If you want to remove everything except alphanumeric characters and underscores, you can simplify it like this:

    $str =~ s/\W//g;
Re: Removing Special Characters
by Anonymous Monk on Nov 01, 2011 at 19:24 UTC

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://935048]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2021-11-27 14:33 GMT
Find Nodes?
    Voting Booth?

    No recent polls found