Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

remove characters by their codes

by Anonymous Monk
on Dec 10, 2007 at 19:34 UTC ( #656202=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hi
i want to remove from a string $str a possible occurrences of characters which have ascii codes :
215,220,224,226,231,232,233,234,235
is it possible to use regular expressions in this case? since such a $str =~ tr/abc//d; will remove the abc chars but the above chars have unclear forms.

Replies are listed 'Best First'.
Re: remove characters by their codes
by kyle (Abbot) on Dec 10, 2007 at 19:43 UTC

    Some other monk will probably post a one-liner, but this should work, and hopefully it's easy to understand. If you don't know of them already, have a look at chr and quotemeta, and maybe ord for good measure.

    my @ascii_be_gone = (215,220,224,226,231,232,233,234,235); my @chars_to_go = map { chr } @ascii_be_gone; my $pattern = join '|', map { quotemeta } @chars_to_go; $str =~ s{$pattern}{}g;
      Since they're characters, not strings, you can use a character class instead of an alternation.
      my @ascii_be_gone = (215,220,224,226,231,232,233,234,235); my @chars_to_go = map { chr } @ascii_be_gone; my ($pattern) = map { qr/[$_]/ } join '', map { quotemeta } @chars_to_ +go; $str =~ s{$pattern}{}g;
Re: remove characters by their codes
by BrowserUk (Pope) on Dec 10, 2007 at 19:44 UTC
Re: remove characters by their codes
by Fletch (Chancellor) on Dec 10, 2007 at 19:45 UTC

    The \xdd escapes (for hex, or \0dd for octal digits, etc.) documented in perlop (search for "Quote and Quote-like Operators") work within a tr statement.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: remove characters by their codes
by artist (Parson) on Dec 10, 2007 at 19:52 UTC
    If they belong to a particular set, we can do better.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://656202]
Approved by kyle
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2018-07-20 14:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (435 votes). Check out past polls.

    Notices?