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

Hi all

I want to extract special characters in the string. for example I have string like:  $str = "Range is <= 4%" Now from this string i would like to find out "<=".But this time is "<=" next time it would ">=". So it is not fixed.

thanks --girija

Replies are listed 'Best First'.
Re: How to extract special charachetrs like <=, >= != from string
by james28909 (Deacon) on Aug 14, 2015 at 05:27 UTC
    If all your trying to do is extract those specific characters, then this might work for you:
    use strict; use warnings; while (<DATA>) { print "$1\n" if $_ =~ /(!=|<=|>=|==)/; } __DATA__ $this <= $that $this lt $that $this >= $that $this gt $that $this != $that $this ne $that $this == $that $this eq $that
    I do suggest you read up on Regular Expressions as it will help you out tremendously on your journey :)

      We can even shorten this with character class []

      use strict; use warnings; use Data::Dumper; while(<DATA>) { print "$1\n" if($_ =~ /([><=!]+)/g) } __DATA__ $this vinoth $that $this >= $that $this gt $that $this != $that $this ne $that $this == $that $this eq $that

      All is well. I learn by answering your questions...
        Hi all,

        Solution provided by james28909 did work for me.

        thanks --girija
        My question to this is, how does it know to print the = after the ><=! ? Maybe i am missing a key piece of data/knowledge which would not surprise me lol.
Re: How to extract special charachetrs like <=, >= != from string
by NetWallah (Canon) on Aug 14, 2015 at 05:41 UTC
    <, > = and ! are not that "special" for regular expressions.

    They can be used inside a "[ ] Bracketed Character class" with capture (see perldoc perlre).

    perl -e '($x=shift()) =~/([=<>!]+)/ and print "\[$x] has \[$1]\n"' "Ra +nge is != 4%" [Range is != 4%] has [!=]

            Clarity: it's like that one thing that is not the other thing, except for when it is.

Re: How to extract special charachetrs like <=, >= != from string
by anonymized user 468275 (Curate) on Aug 14, 2015 at 11:03 UTC
    There is a named posix class [[:punct:]]for characters such as these which are none of \w, whitespace nor control characters. See perlrecharclass

    Update:

    my @puncts = /([[:punct:]]+)/g;

    One world, one people