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

Monks, asking for some guidance on a regex. . I'm trying to do format validation with a cgi script on an item passed back from the form.

The info needs to be entered in form: Any3Characters Underscore AnyCombo of characters ending in underscore ear, so:

..._*_ear ; example: abc_test_test_ear or abc_test_ear

This is somewhat working but not really what I want:
unless (param('AppName') =~ /[^_]*_\(.*\)/) { print "something" exit 1; }

Replies are listed 'Best First'.
Re: Help with form validation regex
by moritz (Cardinal) on May 11, 2009 at 17:18 UTC
    my $regex = qr{ \A # start of string .{3} # any 3 characters _ # underscore .*_ear # anything ending in _ear \z # end of string }xs;

    (Update: fixed ending of string)

Re: Help with form validation regex
by mikeraz (Friar) on May 11, 2009 at 17:23 UTC

    How about:

    #!/usr/bin/perl while(<DATA>) { chomp; if( /\A[\w]{3}_\w+_ear\Z/ ) { print "$_ matches \n"; } else { print "no joy for $_ \n"; } } __DATA__ ab_wehave_noear abc_test_ear abc_test_two_ear abcc_test_ear
    which prints:
    no joy for ab_wehave_noear abc_test_ear matches abc_test_two_ear matches no joy for abcc_test_ear
    I realize your problem definition said "characters" not "word thingies". I'm confident you can munge it to match your expected input range.


    Be Appropriate && Follow Your Curiosity
      I wonder why you write: [\w]{3} instead of \w{3}.

        So do I. The probable thought stream was an intent to specify more than \w and then discarding the idea without discarding the [].

        Bad Michael, no XP today.


        Be Appropriate && Follow Your Curiosity
Re: Help with form validation regex
by JavaFan (Canon) on May 11, 2009 at 18:03 UTC
    /^..._.*_ear$/s
    Or if the fourth character (_) may also be the fourth character from the end:
    /^..._(?:.*_)?ear$/s
    Or even:
    "_" eq substr($_, 3, 1) and "_ear" eq substr $_, -3;
      Yes, he may have been a bit loose on what he meant by "any char". Maybe he meant word chars, or maybe he meant "any char except an underscore". But, you do show that the simplest answer isn't necessary a regex!
        Thanks everyone!

      In your last code snippet I think the ... "_ear" eq substr $_, -3; is only going to look at the last three characters so the condition will never be true.

      $ perl -le ' $str = q{bit_of_a_pigs_ear}; print q{_ear} eq substr( $str, -3 ) ? q{Match found} : q{No match}; print q{_ear} eq substr( $str, -4 ) ? q{Match found} : q{No match};' No match Match found

      I hope this is of interest.

      Cheers,

      JohnGG

Re: Help with form validation regex
by dsheroh (Monsignor) on May 11, 2009 at 18:53 UTC
    In what way is it "not really what [you] want"? Can you provide examples of cases in which your solution provides incorrect results (and what the correct results should be)?