Java Regex checks username length

I am using Java regex to verify username. They must comply with the following restrictions:

  • The username may contain alphanumeric characters and / or underscores (_).

  • The username cannot begin with a numeric character.

  • 8 ≤ | Username | ≤ 30

I got the following regular expression:

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

The problem is that usernames with a length> 30 are not prevented, although one with a length of <8. What happened to my regex?

+5
source share
1 answer

You can use:

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

^[A-Za-z_] provides input with alphabet or underscore, and then [A-Za-z0-9_]{7,29}$ ensures that there will be 7 to 29 word characters at the end, making the 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-30 copies ([A-Za-z_][A-Za-z0-9_]*) , which means starting with an alphabet or underscore followed by the word char of any length.

+11
source

Source: https://habr.com/ru/post/1234004/


All Articles