khalil M khalil M - 1 year ago 89
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}$";

Answer Source

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_].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download