Java Regex validate username length
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.