Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX a-z 0-9 but not only numbers

Tags:

java

regex

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
like image 252
jalmen Avatar asked Dec 25 '22 15:12

jalmen


1 Answers

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}$
like image 130
Wiktor Stribiżew Avatar answered Jan 08 '23 19:01

Wiktor Stribiżew