By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,178 Members | 971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,178 IT Pros & Developers. It's quick & easy.

at lest 2 character in that and a maximum of 3 characters.

P: 33
I am creating a 6 character alpha numeric sting dynamically

i just want to esure that there is at lest 2 character in that and a maximum of 3 characters.
others will be automatically digits (3-4)

I made a regular expression ie like


but is not matching for 22XX22
here i have 4 digits and 2 letters it must be matching
what to do?

Jan 31 '09 #1
Share this Question
Share on Google+
3 Replies

Expert 2.5K+
P: 4,059
Your description of how the string can be constructed is not very clear so unless you can define the possible permuations better here is a generic way to check such a string:

Expand|Select|Wrap|Line Numbers
  1. my $string = '22XX22';
  2. if ($string =~ /[a-zA-Z]{2,3}/ && $string =~ /^[a-zA-Z0-9]{6}$/) {
  3.    print "$string is good\n";
  4. }
  5. else {
  6.    print "$string is bad\n";
  7. }
Jan 31 '09 #2

P: 33
X88X88 should be matched for the regular expression [a-zA-Z]{2,3}, since there are two characters
but this is not matching
Jan 31 '09 #3

Expert 2.5K+
P: 4,059
No, it should not match. You don't understand how {n,n} works. It matches if the characters are in sequence, so XX and XXX will match but not X because it is only one character. Here is a solution that will work no matter where the alpha characters are in the string:

Expand|Select|Wrap|Line Numbers
  1. my $string = 'X88X88';
  2. my $alphas = $string =~ tr/a-zA-Z/a-zA-Z/;#counts the number of characters
  3. if (($alphas == 2 || $alphas == 3) && $string =~ /^[a-zA-Z0-9]{6}$/) {
  4.    print "$string is good\n";
  5. }
  6. else {
  7.    print "$string is bad\n";
  8. }
Jan 31 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.