rahul
rahul

Reputation: 6487

Perl: Why is this pattern matching?

Why is the below pattern match is successful? Am I missing something?

$a="pattern";
if($a =~ /[0-9]*/){
   print "Contains\n";
}

Upvotes: 1

Views: 100

Answers (2)

devnull
devnull

Reputation: 123478

The * quantifier matches 0 or more. And the pattern does match exactly zero digits.

You might want to use + which would denote a match 1 or more times.

Quoting from perldoc perlre:

   Quantifiers

   The following standard quantifiers are recognized:

       *           Match 0 or more times
       +           Match 1 or more times
       ?           Match 1 or 0 times
       {n}         Match exactly n times
       {n,}        Match at least n times
       {n,m}       Match at least n but not more than m times

Upvotes: 10

Richard
Richard

Reputation: 108995

Using * as a quantifier means zero or more instances. In this case it is matching with zero at the position just before the p of the target string.

To match at least one digit use + quantifier instead.

Upvotes: 6

Related Questions