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

喜你入骨 提交于 2021-01-27 11:52:39

问题


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.


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!