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

OK, all-knowing Monks...

I am trying to determine if a variable contains ONLY letters and numbers. If there are any characters besides letters and digits I want the test to fail. I'm using this code and it's not working:

if ($newpasswd !~ /[A-Za-z0-9]/) { EXECUTE SOME THINGS; }
(There is a bracket before the A and after the 9, but it's not showing up in this web page for some reason.)

Any ideas are welcome, thanks!

20050316 Edit by ysth: p & code tags

Replies are listed 'Best First'.
Re: Quickie regular expression question.
by ikegami (Patriarch) on Mar 16, 2005 at 17:16 UTC

    $newpasswd !~ /[A-Za-z0-9]/ means "doesn't contain letters or digits". You want
    $newpasswd !~ /^[A-Za-z0-9]*$/
    ("isn't a string of just letters and digits")
    or even
    $newpasswd !~ /^[A-Za-z0-9]{6,}$/
    ("isn't a string of 6 or more letters and digits")
    to check for a minumum length of 6 at the same time.

    By the way, why are you restricting the password to those characters? It looks like you're weakening security for nothing.

Re: Quickie regular expression question.
by RazorbladeBidet (Friar) on Mar 16, 2005 at 17:16 UTC
    You want
    if ( $newpasswd !~ /^[A-Za-z0-9]+$/ ) { # blah }
    (if you want the "blah" to execute when the variable contains anything EXCEPT ALL letters and/or numbers)
    --------------
    It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
Re: Quickie regular expression question.
by holli (Abbot) on Mar 16, 2005 at 17:18 UTC
    the some reason is that you are not using code-tags.

    As for your question, your code only checks for a single occurence of a digit/letter. Change it to
    if ($newpasswd !~ /^[A-Za-z0-9]+$/) { #EXECUTE SOME THINGS; }
    or even
    if ($newpasswd !~ /^[\w\d]+$/) { #EXECUTE SOME THINGS; }


    holli, /regexed monk/
      [\w\d] is a much bigger set.
      It includes "_" and the chinese character for "one", for example.

      [:alnum:] would be better than \w\d as that's strictly alphanumerics and should respect locale as well.

Re: Quickie regular expression question.
by saintmike (Vicar) on Mar 16, 2005 at 17:19 UTC
    What you're testing is if $newpasswd doesn't contain any characters from the range [A-Za-z0-9].

    What you want instead, is testing if $newpasswd does contain any characters outside the character class [A-Za-z0-9], and then negate the test:

    if ($newpasswd !~ /[^A-Za-z0-9]/) { # EXECUTE SOME THINGS; }
Re: Quickie regular expression question.
by sh1tn (Priest) on Mar 16, 2005 at 17:53 UTC
    if ($newpasswd =~ /(?:\W|_)/) { # EXECUTE SOME THINGS }


Re: Quickie regular expression question.
by rementis (Beadle) on Mar 16, 2005 at 17:48 UTC
    I knew it would be something simple, I really need to get Mastering Regular Expressions.
    Thanks!