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

Hi monks! I am new to perl and especially to regular expressions. Please could you explain me the mechanism of "*" quantifier. For example, we have the following code:
$string = "qwerty 12345"; $string =~ m/([1-5]*)/; print $1;
And after running this script the $1 variable will be empty! Why? "*" means ZERO of SEVERAL matchings so it should match at least one number. Or it shouldn't :) ?

Replies are listed 'Best First'.
Re: Search operator and * quantifier
by moritz (Cardinal) on Jun 20, 2012 at 16:29 UTC

    The overriding principle of the regex engine is that it searches for the left-most possible match of the regex. And the left-most possible match for your regex is the empty string (zero digits) at the start of the string.

    If you don't want that to happen, use the + quantifier instead (one or more matches).

      Thank you!
      I think the regex engine starts at ^ (start of the string), which matches the 1-5*, so it stops. I think the best regex turorial and reference is: http://www.regular-expressions.info/reference.html