khalil M khalil M - 1 month ago 6x
Java Question

pattern of regex

I am new in Regex, I want to validate words with at least 6 characters and max 30 and should start with letters only but it can contain numbers and underscore starting from second position.I used this pattern but it failed in tests.

String pattern = "^[A-Za-z][A-Za-z0-9_]*{6,30}$";


You can use this regex:

String pattern = "^[A-Za-z][A-Za-z0-9_]{5,29}$";
  • You must not use * before range quantifier {5,29}.
  • Using {5,29} because 1 character is already at the start.

You can also use this shortened regex:

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

As \w (word character) is equivalent of [A-Za-z0-9_].