Remove Unicode control character from string

Discussion in 'Perl Misc' started by Ryan Chan, Oct 4, 2009.

  1. Ryan Chan

    Ryan Chan Guest

    Hello,

    Consider the sample code:
    ##############
    use strict;

    my $in = "\U0004";
    my $out = chr($in) . "apple";

    $out =~ s/[:cntrl:]//gi;
    print $out;
    ##############

    I want to remove the the first unicode char (e.g. "\U0004") from the
    string, I found the above code does not work as expected, any idea?

    Thanks.
     
    Ryan Chan, Oct 4, 2009
    #1
    1. Advertising

  2. Ryan Chan

    Ben Bullock Guest

    On Oct 4, 11:30 pm, Ryan Chan <> wrote:
    > Hello,
    >
    > Consider the sample code:
    > ##############
    > use strict;
    >
    > my $in = "\U0004";
    > my $out = chr($in) . "apple";
    >
    > $out =~ s/[:cntrl:]//gi;
    > print $out;
    > ##############
    >
    > I want to remove the the first unicode char (e.g. "\U0004") from the
    > string, I found the above code does not work as expected, any idea?


    I got a message like this:

    POSIX syntax [: :] belongs inside character classes in regex; marked
    by <-- HERE
    in m/[:cntrl:] <-- HERE / at ./moo.pl line 6.

    It seems you need more []s.

    $out =~ s/[[:cntrl:]]//gi;

    seems to do the trick.
     
    Ben Bullock, Oct 4, 2009
    #2
    1. Advertising

  3. Ryan Chan <> wrote:
    >$out =~ s/[:cntrl:]//gi;
    >
    >I want to remove the the first unicode char (e.g. "\U0004") from the
    >string, I found the above code does not work as expected, any idea?


    You can use the notation [:cntrl:] only inside of a character class.
    From "perldoc perlre":

    The POSIX character class syntax

    [:class:]

    is also available. Note that the "[" and "]" brackets are *literal*;
    they must always be used within a character class expression.

    # this is correct:
    $string =~ /[[:alpha:]]/;

    # this is not, and will generate a warning:
    $string =~ /[:alpha:]/;

    jue
     
    Jürgen Exner, Oct 4, 2009
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Daniel Mark
    Replies:
    6
    Views:
    70,782
    Tim Chase
    Sep 28, 2006
  2. Kenneth McDonald
    Replies:
    1
    Views:
    843
    Carl Banks
    Dec 27, 2006
  3. Tyler
    Replies:
    1
    Views:
    953
    Robert Klemme
    Jul 29, 2011
  4. An. Valula
    Replies:
    3
    Views:
    184
    Alan J. Flavell
    Oct 23, 2003
  5. Bart Vandewoestyne
    Replies:
    8
    Views:
    742
    Bart Vandewoestyne
    Sep 25, 2012
Loading...

Share This Page