Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How to match for exact length of multiple values?

Tags:

java

regex

How can I use this pattern: [A-Za-z0-9]{10} to also match to other text sizes like: 12 and 25?

I tried to make it like:

  1. [A-Za-z0-9]{10|12|25}
  2. ([A-Za-z0-9]){10}|{12}|{25}

But it didn't succeed.

like image 971
The Dr. Avatar asked Dec 09 '22 00:12

The Dr.


1 Answers

You need to use alternations if you need to match specific sized only:

^(?:[A-Za-z0-9]{10}|[A-Za-z0-9]{12}|[A-Za-z0-9]{25})$

If you want to match symbols within a range, say, from 10 to 25, you can use

^[A-Za-z0-9]{10,25}$

Also, [A-Za-z0-9] can be replaced with \p{Alnum} (see Java regex reference).

\p{Alnum} An alphanumeric character:[\p{Alpha}\p{Digit}]

Java code demo with String#matches (that does not require anchors):

System.out.println("1234567890".matches("[A-Za-z0-9]{10}|[A-Za-z0-9]{12}|[A-Za-z0-9]{25}")); 
// => true, 10  Alnum characters
System.out.println("12345678901".matches("\\p{Alnum}{10}|\\p{Alnum}{12}|\\p{Alnum}{25}"));
// => false, 11 Alnum characters
System.out.println("123456789012".matches("\\p{Alnum}{10}|\\p{Alnum}{12}|\\p{Alnum}{25}"));
// => true, 12  Alnum characters
like image 82
Wiktor Stribiżew Avatar answered Dec 10 '22 14:12

Wiktor Stribiżew