That snippet is quite inefficient, and will fail to work sometimes.
First, the '*' quantifier does too much work. Look for a second at what '*' is going to do. Let's assume the following string:
my $string = "xyzzyzx";
When you test that with your regexp, because of the greedy '*' quantifier placed between a ^ and $ beginning of string and end of string zero-width assertion, you get this behavior:
$string =~ /^[xyz][xyz][xyz][xyz][xyz][xyz][xyz]$/;
In other words, the regexp engine uses the '*' quantifier to build up a very big chain of character classes, which is essentially the same as saying /^[xyz]{7}$/. The longer the string you're scanning, the more [xyz] character classes are built up into the regexp.
The second problem is that /^[xyz]*$/ will match a string of zero length, or an empty string. Here's why. The '*' quantifier will match zero or more times. The ^ and $ assertions tell the regexp engine that your regexp must match from the beginning to the end of the string. Fine. So if the string contains only one 'x', you've got a match. If it contains many characters from the [xyz] character class, you've also got a match. But you know what? If you have NO characters, the '*' does just as it's supposed to do, and matches successfully. And ^ and $ are happy, because their requirement has been met as well; the string has been matched from start to finish (even though there's nothing there at all).
Your regexp would at least work (with less than optimal performance) if you change the '*' quantifier to a '+' quantifier. Then it would be on track.
I posted an even more efficient solution here: Re: matching all characters within a string?.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
In reply to Re: Re: matching all characters within a string?
by davido
in thread matching all characters within a string?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |