in reply to check if string contains anything other than alphanumeric

I want to make sure it ONLY has a-z, A-Z and 0 to 9

Your description is at odds with the example you gave. The string "hello world" contains a space - which is not an alphanumeric character, and not part of the character class [a-zA-Z0-9]

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: check if string contains anything other than alphanumeric
by Anonymous Monk on Aug 12, 2007 at 08:25 UTC
    Yup, ur right. lol, sorry. I was typing very fast and did not even realize it. this did work though:
    if ($value =~ m/[^a-zA-Z0-9]/) {
    So thank you very much!!!

    I do have a question though, why does that work, since it is not !~ and is =~?

    Oh well, it does work and that is all that matters!

    Thanks again.
      If a character class starts with ^, it is a negated character class. That is, it will match any character that is not in the class. So, /[^a-zA-Z0-9]/ will match any character that is not a letter or digit.

      See perlretut for a tutorial on regexps and perlre for the details.

      update: My 200th node :)

      I do have a question though, why does that work, since it is not !~ and is =~?
      It reads more or less "it's true if the string contains (=~) something other (^) than letters and numbers (a-zA-Z0-9)", so it works.

      You can of course use !~ as well, to say "it's true if the string doesn't contains (!~) one or more letters and numbers ([a-zA-Z0-9]+) in its entirety (hence the ^ and $ that constitutes the start and end marks).

      print "bad string: $string\n" if $string !~ /^[a-zA-Z0-9]+$/;
      which I prefer to write (yes back to =~ and not !~):
      print "bad string: $string\n" unless $string =~ /^[a-zA-Z0-9]+$/;

      Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!