3

I want a script to select a username. The rules for selecting a username are:

  • The minimum length of the username must be 5 characters and the maximum may be 10.
  • It should contain at least one letter from A-Z
  • It should contain at least one digit from 0-9
  • It should contain at least one character from amongst @#*=
  • It should not contain any spaces.

I have tried this:

if (( length $passwd[$i]<=10 && length $passwd[$i]>=5 && $passwd[$i] =~ /.*\p{Lu}/ && $passwd[$i] =~ tr/0-9//cd  && $passwd[$i] =~ /[a-z]/ ))
{   
    print "PASS\n";
}
else
{
    print "FAIL\n";
}
Ricky
  • 51
  • 8

1 Answers1

3

As one perl regular expression, that could be:

if ($username =~ qr{^(?=.*[A-Z])(?=.*\d)(?=.*[@#*=])(?!.* ).{5,10}$}s) ...

Or:

if ($username =~ qr{^(?=.*[A-Z])(?=.*\d)(?=.*[@#*=])[^ ]{5,10}$}s)
Stephane Chazelas
  • 5,859
  • 2
  • 34
  • 31
  • thank you sir. its working in command promt. but how can i use it in my script. i am like two days old in perl. so please be co-operative. i know i somehow asking very silly question.. – Ricky Dec 14 '13 at 13:00
  • Your regex says `Perl #42` is OK. – Kenosis Dec 15 '13 at 05:19
  • @Kenosis, oops thanks, `(?!=` should have been `(?!`. Fixed now. – Stephane Chazelas Dec 15 '13 at 12:34
  • Yes--well done. You can omit the `/s` modifier, as it's used to treat a newline-containing string as a **s** ingle string, where the metacharacter `.` would then match `\n`. – Kenosis Dec 15 '13 at 16:45
  • @Kenosis, which is why I used `s`, or otherwise they would say that `"Abc\n9#"` is not a valid username. – Stephane Chazelas Dec 15 '13 at 19:44
  • Hmm... Perhaps the OP's specs are not so clear, since I can't see that `"Abc\n9#"` *should* be a valid user name. That is, I wonder if (white)spaces was intended, as `"Abc\t\r\n9#"`, etc., would be valid. For example, `"Perl\x0E#42"` is valid, but contains a [vertical tab](http://my.safaribooksonline.com/book/web-design-and-development/0596102356/data-integrity-and-security/web2apps-chp-5-sect-4). Regardless, given the OP's specs, your regex does the job well (+1). – Kenosis Dec 15 '13 at 20:13