develooper Front page | perl.beginners | Postings from February 2002

RE: Allow only letters and numbers?

Thread Previous | Thread Next
From:
Timothy Johnson
Date:
February 21, 2002 17:27
Subject:
RE: Allow only letters and numbers?
Message ID:
C0FD5BECE2F0C84EAA97D7300A500D5002580FB6@SMILEY

If you don't mind having underscores in your text, you could also do this:

if($string !~ /^\w+$/){  #If the string does not have only letters, digits,
and underscores from start to finish (\w)
   print "There's a special character in there somewhere.\n";
}

-----Original Message-----
From: Jeff 'japhy' Pinyan [mailto:jeffp@crusoe.net]
Sent: Thursday, February 21, 2002 4:57 PM
To: Daniel Falkenberg
Cc: beginners@perl.org
Subject: Re: Allow only letters and numbers?


On Feb 22, Daniel Falkenberg said:

>The code below of coarse will count all characters in the string $string
>
>$string = "4556jhkl";
>
>$count = $string =~ tr/a-zA-Z0-9//;
>
>How would I go about only allowing numbers and letters of the alpahbet?

You could say:

  if ($string =~ tr/a-zA-Z0-9//c) {
    print "bad character found";
  }

The /c modifier means "invert the set", so that tr/aeiou//c scans for
characters that are NOT a, e, i, o, or u.

If a regex is want you want to use, I'd suggest:

  if ($string =~ /[^a-zA-Z0-9]/) {
    # bad character found
  }

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org


--------------------------------------------------------------------------------
This email may contain confidential and privileged 
material for the sole use of the intended recipient. 
If you are not the intended recipient, please contact 
the sender and delete all copies.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About