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

Given the following code:
#!/usr/bin/perl use strict; sub test($); test 'a'; test 'z'; test 'xyz'; test 'az'; sub test($) { my $s = shift; print $s =~ /[xyz]/ ? "$s matches\n" : "$s does not match\n"; }
I want all characters tested against the RE character class to match in order for the overall string to match. String 'az' matches above whereas I want the presence of character 'a' to cause the overall string to fail as the following code does correctly:
#!/usr/bin/perl use strict; sub test($); test 'a'; test 'z'; test 'xyz'; test 'az'; sub test($) { my $s = shift; for my $c (split '', $s) { if ($c !~ /[xyz]/) { print "$s does not match\n"; return; } } print "$s matches\n"; }
Is there a simpler way with regular expressions to accomplish what I want?

Thanks.

Replies are listed 'Best First'.
Re: matching all characters within a string?
by davido (Cardinal) on Sep 23, 2003 at 18:21 UTC
    I want to show you three ways. The first one illustrates how the second one works. The second one illustrates how the third one works. The first two are inefficient, but are sort of building blocks toward understanding the third. Here's the messy and inefficient way to do it. :)

    sub test { my $s = shift; my $l = length $s; if ($s =~ /[xyz]{$l}/) { print "$s matches\n"; return; } print "$s doesn't match\n"; }

    The principle is that you're repeating the character class [xyz] as many times as there are characters in the string using the '{n}' quantifier. Now here's a more efficient way that follows a similar principle, but eliminates the need for you doing the counting yourself.

    sub test { my $s = shift; if ( $s =~ /^[xyz]+$/ ) { print "$s matches\n"; return; } print "$s doesn't match\n"; }

    Now the character class [xyz] must match each character from the start to the end of the string because of the '+' quantifier. We've introduced the ^ and $ assertions, which are telling the regexp that it can only match if the string starts and ends with a match, and since there's only one thing that can match, repeated a bunch of times with the + quantifier, it means that only a string containing nothing but a bunch of x's, y's, and z's will match. Think of the ^ and $ as stretching the + quantifier to fit from the beginning to the end of the string.

    The problem with the first two methods is that you've got to match a character class repeatedly throughout every character of the string. This isn't particularly efficient. In fact, it's worse than you might imagine. It means that every time through the test, every character needs to be tested several ways.

    There is yet another way to do it that is much more efficient:

    sub test { my $s = shift; if ( $s =~ /[^xyz]/ ) { print "$s contains non-xyz characters.\n"; return; } print "$s does not contain non-xyz characters.\n"; }

    Notice that this method is a little backwards. Instead of focusing on whether the string contains something repeatedly from start to finish, this method focuses on whether anything BUT what we want exists within the string, by using a negated character class. No quantifier is needed, because we only care if there is even one existance of a dirty character (a non-xyz character). For the same reason, no ^ and $ is are needed. This will be a more efficient regexp, and probably the best choice. This match succeeds and terminates as soon as the first non-xyz character is found. That's a big win. Just be sure to understand the logic.

    I hope this helps.

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Re: matching all characters within a string?
by bart (Canon) on Sep 23, 2003 at 19:01 UTC
    A simple way is to invert the logic: reject the string if there's anything found that doesn't match with what you like. So you invert your character class, and you negate your test.
    if(/[^xyz]/) { # It matches, though it shouldn't print "No good."; return 0; } else { print "Acceptable"; return 1; }
Re: matching all characters within a string?
by Thelonius (Priest) on Sep 23, 2003 at 18:12 UTC
    sub test($) { my $s = shift; print $s =~ /^[xyz]*$/ ? "$s matches\n" : "$s does not match\n"; }
          print $s =~ /^[xyz]*$/ ? "$s matches\n" : "$s does not match\n";

      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