Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

remove characters by their codes

by Anonymous Monk
on Dec 10, 2007 at 19:34 UTC ( [id://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 (Patriarch) on Dec 10, 2007 at 19:44 UTC
Re: remove characters by their codes
by Fletch (Bishop) 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
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://656202]
Approved by kyle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-03-28 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found