4

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
jalmen
  • 191
  • 1
  • 9

2 Answers2

9

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}$
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

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

Demo

More details

Community
  • 1
  • 1
Ahosan Karim Asik
  • 3,219
  • 1
  • 18
  • 27