问题
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:
[A-Za-z0-9]{10|12|25}([A-Za-z0-9]){10}|{12}|{25}
But it didn't succeed.
回答1:
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
回答2:
You could have
([A-Za-z0-9]){10}|([A-Za-z0-9]){12}|([A-Za-z0-9]){25}
Note that [A-Za-z0-9] can be expressed more simply with \p{Alnum}, making the regex:
(\\p{Alnum}){10}|(\\p{Alnum}){12}|(\\p{Alnum}){25}
回答3:
to avoid useless work for the regex engine, you can write:
[A-Za-z0-9]{10}(?:[A-Za-z0-9]{2}(?:[A-Za-z0-9]{13})?)?
in this way the first characters are parsed only once.
来源:https://stackoverflow.com/questions/34311964/regex-how-to-match-for-exact-length-of-multiple-values