i trying construct regular expression accepts alphanumerics ([a-za-z0-9]), except single hyphen (-) in middle of string, minimum of 9 characters , maximum of 20 characters.
i have verified following expression, accepts hyphen in middle.
/^[a-za-z0-9]+\-?[a-za-z0-9]+$/  how can set minimum 9 , maximum 20 characters above regex? have used quantifiers + , ? in above expression. 
how apply {9,20} above expression? there other suggestions expression?
/^[a-za-z0-9]+\-?[a-za-z0-9]+$/ can simplified to
/^[a-z0-9]+(?:-[a-z0-9]+)?$/i since if there no dash don't need more letters after it, , can use i flag match case-insensitively , avoid having reiterate both lower-case , upper-case letters.
then split problem 2 cases:
- 9-20 alpha numerics
- 10-21 characters, of alpha numerics except 1 dash
you can check second using positive lookahead like
/^(?=.{10,21}$)/i to check number of characters without consuming them.
combining these gives you
/^(?:[a-z0-9]{9,20}|(?=.{10,21}$)[a-z0-9]+-[a-z0-9]+)$/i 
Comments
Post a Comment