9

I'm using Java regex to validate an username. They have to meet the following constraints:

  1. Username can contain alphanumeric characters and/or underscore(_).

  2. Username can not start with a numeric character.

  3. 8 ≤ |Username| ≤ 30

I ended up with the following regex:

String regex="^([A-Za-z_][A-Za-z0-9_]*){8,30}$";

The problem is that usernames with length > 30 aren't prevented although the one with length < 8 are prevented. What is the wrong with my regex?

2 Answers 2

14

You can use:

String pattern = "^[A-Za-z_][A-Za-z0-9_]{7,29}$";

^[A-Za-z_] ensures input starts with an alphabet or underscore and then [A-Za-z0-9_]{7,29}$ makes sure there are 7 to 29 of word characters in the end making total length 8 to 30.

Or you can shorten it to:

String pattern = "^[A-Za-z_]\\w{7,29}$";

You regex is trying to match 8 to 30 instances of ([A-Za-z_][A-Za-z0-9_]*) which means start with an alphabet or underscore followed by a word char of any length.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

"^[A-Za-z][\\w_]{7,29}$"

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.