ndrone ndrone - 2 months ago 7
Java Question

Regex first character must be alpha if more than one character can include numbers and underscore up to 128

As the long title suggests if the test string has only character it can only be alpha. But if the test string has more than one character up to 128 characters then it still must start with an alpha character but then allow numbers and underscores.

This is the regex I have so far.

^([a-zA-Z])|([a-zA-Z][A-Za-z0-9\_]{2,128})$


where it fails is if the second character is an underscore.

Here is the link: https://regex101.com/r/xzmfRs/1

Answer

You can use this regex for your problem:

^[a-zA-Z]\w{0,127}$

To allow one alphabet or else allow upto 128 characters of word characters.

\w is shorthand for [a-zA-Z0-9_]

Updated RegEx Demo