CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
alphanumeric

 



perlkid
stranger

Feb 17, 2000, 8:27 PM

Post #1 of 6 (1052 views)
alphanumeric Can't Post

 
How Do I check to see if a string is only letters and not numbers and if a string is only numbers and not letters?

I thought I was sonthing like this,

if ($string =~ [A-Za-z]
{
only letters
}
elseif ($string =~ [0-9])
{
only numbers
}

perlkid


Cure
User

Feb 17, 2000, 8:36 PM

Post #2 of 6 (1052 views)
Re: alphanumeric [In reply to] Can't Post

NOTE:

In C++ its elseif
in PERL its elsif

Cure


kencl
User

Feb 17, 2000, 11:03 PM

Post #3 of 6 (1052 views)
Re: alphanumeric [In reply to] Can't Post

You're close. Try:

if ($string !~ [A-Za-z]
{
only numbers
}
elseif ($string !~ [0-9])
{
only letters
}



perlkid
stranger

Feb 18, 2000, 12:14 AM

Post #4 of 6 (1052 views)
Re: alphanumeric [In reply to] Can't Post

 
Thanks,

kencl--- I'll try that tomorrow but for now I have to wake up early tomorrow.

cure--- thanks for correcting my syntax error.

perlkid


japhy
Enthusiast

Feb 18, 2000, 5:47 AM

Post #5 of 6 (1052 views)
Re: alphanumeric [In reply to] Can't Post

kencl, perlkid -- you're missing the regular expression delimiters (the /'s).

To find out if a string is ONLY letters, I'd suggest doing:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


if ($string !~ /[^A-Za-z]/) {
# $string does not have any non-letters
}
</pre><HR></BLOCKQUOTE>

I suggest that, INSTEAD OF

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


if ($string =~ /^[A-Za-z]+$/) {
# $string has all letters
}
</pre><HR></BLOCKQUOTE>

for TWO reasons. First, the one I suggest is
an application of logic (if $string is all letters, then it CAN'T have non-letters). Second, is because the $ anchor in a regex can match directly before a newline (which is NOT a letter). You can get around that by saying:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


if ($string =~ /^[A-Za-z]+(?!\n)$/) {
# ...
}
</pre><HR></BLOCKQUOTE>

Anyway. To match a string as all numbers, I'd suggest:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


if ($string !~ /\D/) {
# \d is the [0-9] char class
# \D is non-digits
}
</pre><HR></BLOCKQUOTE>

Thus endeth the lesson.

[This message has been edited by japhy (edited 02-18-2000).]


perlkid
stranger

Feb 19, 2000, 10:06 AM

Post #6 of 6 (1052 views)
Re: alphanumeric [In reply to] Can't Post

 
Thanks japhy,

You saved me a good 20 minuts of frustration.

perlkid

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives