And what about the sample strings? Did it match any of them? You bet:
it matches all of them! It's because the backslashes and
asterisks aren't required in the pattern; that is, this pattern
can match the empty string. Here's a rule you can rely upon:
when a pattern may freely match the empty
string, it'll always match, since the
empty string can be found in any string. In fact, it'll always
match in the first place that you look.
So, this pattern matches all four characters in
\\**, as you'd expect. It matches the empty
string at the beginning of fred, which you may not
have expected. In the string barney \\\***, it
matches the empty string at the beginning. You might wish it would
hunt down the backslashes and stars at the end of that string, but it
doesn't bother. It looks at the beginning, sees zero
backslashes followed by zero asterisks, declares the match a success,
and goes home to watch television. And in *wilma\,
it matches just the star at the beginning; as you see, this pattern
never gets away from the beginning of the string, since it always
matches at the first opportunity.
Now, if someone asked you for a pattern to match any number of
backslashes followed by any number of asterisks, you'd be
technically correct to give them this one. But chances are,
that's not what they really wanted. Spoken languages like
English may be ambiguous and not say exactly what they mean, but
regular expressions always mean exactly what they say they mean.
In this case, maybe the person who asked for the pattern forgot to
say that he or she always wants to match at least one character, when
the pattern matches at all. We can do that. If there's at least
one backslash, /\\+\**/ will match. (That's
just like what we had before, but there's a plus in place of
the first star, meaning one or more backslashes.) If there's
not at least one backslash, then in order to match at least one
character, we'll need at least one asterisk, so we want
/\*+/. When you put those two possibilities
together, you get:
/\\+\**|\*+/
Ugly, isn't it? Regular expressions are powerful but not
beautiful. And they've contributed to Perl being maligned as a
"write-only language." To be sure that no one criticizes
your code in that way, though, it's kind to put an explanatory
comment near any pattern that's not obvious. On the other hand,
when you've been using these for a year, you will have a
different definition of "obvious" than you have today.
How does this new pattern work with the sample strings? With
\\**, it matches all four characters, just like
the last one. It won't match fred, which is
probably the right behavior given the problem description. For
barney \\\***, it matches the six characters at
the end, as you hoped. And for *wilma\, it matches
the asterisk at the beginning.