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


I'd like to extract all alphanumeric characters from a given string and store them into another string. How can i achieve this?

  • Comment on How to extract all alphanumeric characters from a string?

Replies are listed 'Best First'.
Re: How to extract all alphanumeric characters from a string?
by ikegami (Patriarch) on Nov 13, 2009 at 21:13 UTC
    utf8::upgrade( my $alphanums = $chars ); $alphanums =~ s/[\W_]//g;
    or
    ( my $alphanums = $chars ) =~ s/\P{Alnum}//g;

    utf8::upgrade makes /\w/ match alphanums and "_", and /\W/ everything else.

    Update: The original solution didn't remove underscores. Fixed.
    Update: Added alternative method.