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: Regular Expressions:
Validate string

 



mhassan
Novice

Jan 21, 2010, 9:31 AM

Post #1 of 3 (2914 views)
Validate string Can't Post

Hi,
I want to check if the $mystring variable is less than or equal to 3 characters using regex. If variable string is less than or equal to 3 then print "your string is less than or equal to 3 characters". Below is my test code.


Code
#!/usr/bin/perl -w 

use strict;

my $mystring = "lsdkajsssssssssssssssssssssfkljadskljfkldsaj";
my $regex = ".{0,3}";

if ($mystring =~ m/.{0,3}/){

print "your string is less than or equal to 3 characters\n";
}

exit;


This code prints "your string is less than or equal to 3 characters" even though i don't want the it to since $mystring is larger than 3 characters. I don't know anything about regex. Any help?


toolic
User

Jan 21, 2010, 9:51 AM

Post #2 of 3 (2908 views)
Re: [mhassan] Validate string [In reply to] Can't Post

If you really think you need to use a regex, then you should anchor the pattern:


Code
if ($mystring =~ m/^.{0,3}$/){


However, using the built-in length function seems more appropriate than a regex for this task:


Code
if (length($mystring) <= 3) {



mhassan
Novice

Jan 21, 2010, 10:57 AM

Post #3 of 3 (2907 views)
Re: [toolic] Validate string [In reply to] Can't Post

Thanks a lot it works!. I needed to use regex to check length since $mystring and $regex is one of the element of an array. The above code was just a test code..

 
 


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

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