in reply to Puzzled by regex

In the first regular expression you're using the '?' operator which says the previous character or group is optional. But you're applying it against the '+' operator which makes no sense, since it means one-or-more.

If instead you group the \S and + together and then apply the '?', you'll see different results:

use warnings; my @str = ("____\n", "__ __\n", "__X __\n", "__Z__\n", "__\n__\n", "__ +^__\n"); for(@str) { if($_ =~ /__(\S+)?__\n/) {print "1 "} else {print "0 "} if($_ =~ /__\S+__\n/) {print "1\n"} else {print "0\n"} } __END__ 1 0 0 0 0 0 1 1 0 0 1 1

So the answer is, Inline.pm just has a bug.

Replies are listed 'Best First'.
Re^2: Puzzled by regex
by davido (Cardinal) on Apr 10, 2013 at 06:04 UTC

    This is not exactly accurate. \S+ greedily matches one or more non-space characters. \S+? non-greedily matches one or more non-space characters. The syntax does make sense.


    Dave

      David,

      Thanks for correcting me. I was just dead wrong.

      It's explained here: Matching Repititions, Down a bit it explains, "minimal match or non-greedy quantifiers ?? , *? , +?, and {}?"

      Learn something new every day.

        Nothing to be ashamed of. ;) I often remind myself to leave regex-related questions alone because they're so hard to answer correctly.


        Dave