Is this Regex correct if I have to match a string which is atleast 7 characters long, not more than 20 characters, has atleast 1 number, and atleast 1 letter? It has no other constraints.
[0-9]+[A-Za-z]+{7,20}
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, it’s not. The quantifier
{7,20}doesn’t apply to a token (repetition in regexes is done with quantifiers, like*,+,?or the more general{n,m}– you cannot use more than one quantifier on a single token [in this case[a-zA-Z]];*?is a quantifier on its own and thus doesn’t play by above rules). You’ll need something like the following:This has two lookaheads making sure of at least one digit and at least one letter:
Lookarounds are zero-width assertions; they do not consume characters in the string so they are merely matching a position. But they make sure that the expression inside of them would match at the current point. In this case this expression would match arbitrarily many characters and then would require a digit or a letter, respectively.
The actual match itself,
just makes sure the length matches. What characters are used is irrelevant because we made sure of that constraints above already.
Finally the whole expression is anchored in that a start-of-string and end-of-string anchor are inserted at the start and end:
This makes sure that the match really encompasses the whole string. While not strictly necessary in this case (it would match the whole string anyway in all valid cases) it’s often a good idea to include because usually regexes match only substrings and this can lead to subtle problems where validation regexes match even though they should fail. E.g. using
\d+to make sure a string consists only of digits would match the stringa4bwhich puzzles beginners quite often.I also changed that the order of letters and numbers doesn’t matter. Your regex looks like it tries to impose a definite order where all numbers need to come before all letters which usually isn’t what’s wanted here.