Question

I need to write a regular expresssion for a string to match [a-zA-z0-9-._,\s] character set only. Other than the mentioned character set , it should throw an error. Also, the length of the string could be 30 characters only. I implemented word wrap also. But, i am not able to throw error if the string is other than the mentioned character set. Any help would be much appreciated!

My string looks like :

   shubhwork1234  567$#@!%^&*()<>:"-,._abadcew

My code should throw an error - stating that only [a-zA-z0-9-._,\s] character set is allowed.

If my string is below : then there should be NO error.

   shubhworkwwwwwwwww1234567-,._  abadcew

My code looks like :

   #!/usr/bin/perl
   my $prodname;
   my $temp_str;
   my $space = ' '; # word wrap done usign space character
   $prodname = "shubhwork1234  567$#@!%^&*()<>:"-,._abadcew";
   print (Product name not specified-name 1\n) unless($prodname);
   print "\n Product name is : $prodname";

   # For Product name , only 30 characters are allowed.
   print "\nLength of product name : ",length($prodname),"\n";    
   if(length($prodname) > 30)
   {
        print "\n Hello world";
            $temp_str = substr($prodname,0,40);
            print qq| Length of Product Name can be 40 characters.Terminating rest of the string\n|);

  #Handling xml special characters >,<,&,",'
     $temp_str =~ s/&/&amp;/g; 
     $temp_str =~ s/</&lt;/g;
     $temp_str =~ s/>/&gt;/g;
     $temp_str =~ s/"/&quot;/g;
     $temp_str =~ s/'/&apos;/g;
     $temp_str =~ s/[\x00-\x08\x0B\x0C\x0E-\x19]//g;

     # Word wrap
     my $rindx = rindex($temp_str,$space);
     $temp_str = substr($temp_str,0,$rindx);
     print "\n Sting temp is : $temp_str";

     #Here I ma not able to use negate properly for the character set. 
     if ($temp_str =~ m/^[a-zA-Z0-9]-._,\s*/)
     {
        print (qq| For product name : Invalid Input : Only [a-zA-Z0-9-._,] and spaces are allowed\n|);
     }                  
       $prodname = $temp_str; 
      print "\n assigning string is :",$prodname;
     }
Was it helpful?

Solution

Closing square bracket in wrong spot, you forgot the trailing \z, and you forgot to negate.

if ($temp_str !~ /^[a-zA-Z0-9-._,\s]*\z/)  # Doesn't consist of good characters

or you could use

if ($temp_str =~ /[^a-zA-Z0-9-._,\s]/)  # Contains a non-good character

Note that \s matches a number of different whitespace character, not just the space.

OTHER TIPS

Since you also want to check the length, you don't need to negate it. You can just check that the entire string is 30 or fewer of the allowed characters:

/\A[a-zA-z0-9-._,\s]{0,30}\z/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top