Vamsikrishna
Vamsikrishna

Reputation: 176

Regular Expression allows more than specified characters

HI I am new to regular expression, I tried creation regular expression based on below conditions:

  1. Maximum 9 characters are allowed

  2. First character must be upper case

  3. Ending character must be 0-9

  4. Must contain following special character ($,%,#)

    /^[A-Z][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\d+$/
    

What is wrong in my regular expression?

Upvotes: 2

Views: 59

Answers (2)

vks
vks

Reputation: 67968

^[A-Z](?=.*[#$%])[a-z0-9A-Z$#%]{1,7}\d$

You need to take the lookahead at the start.\d+ should be \d.{3,9} should be {1,7}

Upvotes: 1

Welbog
Welbog

Reputation: 60418

Breaking the regex down

/^[A-Z][a-z0-9A-Z$#%]{3,9}(?=.*[#$%]).\d+$/
^ # Match the start of a string
[A-Z] # First character must be a capital letter
[a-z0-9A-Z$#%]{3,9} # The next 3-9 characters must be alphanumeric or one of $, # and %.
(?=.*[#$%]) # Look-ahead, requiring that some character be one of $, # and % (note that this is strictly after the 3-9 character check)
. # Match any character
\d+ # Match one or more numeric digits
$ # Match the end of the string

Therefore a string like "Aaaa$^55555555555555555" would be matched.

You need to change your look-ahead, probably moving it to before the 3-9 character check. You'll also want to make the length of that smaller, since you're explicitly allowing a capital letter as the first character and digit as the last character, so you'll probably want to match 1-7 characters instead of 3-9.

Upvotes: 0

Related Questions