0

I'm trying to validate a form field in Java using Regex, which can have 5 different format possibilities. I'm struggling to get this one working.

The string to be checked will be between 4-6 alphanumeric characters.

If it's 4 characters, it must be all numbers.

^\\d{4}$

If it's 5 characters, it can be all numbers, first position letter with 4 following numbers, or first 3 positions letters followed with 2 numbers.

 ^\\d{5}$
 ^[a-zA-Z]\\d{4}$
 ^[a-zA-Z]{3}\\d{2}$

And if it's 6 characters, it will be first position letter, 4 numbers, and last another letter.

^[a-zA-Z]\\d{4}[a-zA-Z]$

I just can't seem to piece it all together though.

4

1 回答 1

2

最简单的方法是列出一组中的每个可接受的模式,用交替 ( |) 分隔:

^(\\d{4}|\\d{5}|[a-zA-Z]\\d{4}|[a-zA-Z]{3}\\d{2}|[a-zA-Z]\\d{4}[a-zA-Z])$

但是您可以通过结合一些替代方案来稍微改善这一点:

^([a-zA-Z\\d]?\\d{4}|[a-zA-Z]{3}\\d{2}|[a-zA-Z]\\d{4}[a-zA-Z])$
于 2013-09-13T03:32:21.333 回答