jalmen
jalmen

Reputation: 301

REGEX a-z 0-9 but not only numbers

Trying to match only strings 10-30 characters long with only a-z and 0-9 (but not only numbers) in the string. Seems to work Except when the string starts with a number then it fails. Not sure about the \D which should fix the not only numbers

static final Pattern UNIQUE_ID_PATTERN = Pattern.compile("^\\D[A-Za-z0-9_-]{10,30}$");
UNIQUE_ID_PATTERN.matcher("1eeeeeeeee333e").matches(); // Does not work
UNIQUE_ID_PATTERN.matcher("eeeeeeeee333e").matches(); // Works

Upvotes: 5

Views: 3755

Answers (2)

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Another way: ^(?=(?:.*[a-zA-Z])+)([a-zA-Z\d]{10,30})$ update

Demo

More details

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

The \D shorthand class means any non-digit symbol. You should remove it from the pattern (so that it becomes "^[A-Za-z0-9_-]{10,30}$") for the matches to return true, as 1 is a digit in 1eeeeeeeee333e.

If you want to place a restriction (the string cannot consist of only digits) use an anchored look-ahead:

^(?![0-9]+$)[A-Za-z0-9_-]{10,30}$

Here is a demo

Or, a shortened version with i modifier making the pattern case-insensitive:

(?i)^(?![0-9]+$)[A-Z0-9_-]{10,30}$

Upvotes: 10

Related Questions