试一试:
/^(C\d{4}[a-zA-Z]\d{7}|[a-zA-Z]{2}\d{6}[a-zA-Z]?|\d{9})$/
我想最后一个 alpha 在规则 #2 中是可选的
解释:
The regular expression:
(?-imsx:^(C\d{4}[a-zA-Z]\d{7}|[a-zA-Z]{2}\d{6}[a-zA-Z]?|\d{9})$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
C 'C'
----------------------------------------------------------------------
\d{4} digits (0-9) (4 times)
----------------------------------------------------------------------
[a-zA-Z] any character of: 'a' to 'z', 'A' to 'Z'
----------------------------------------------------------------------
\d{7} digits (0-9) (7 times)
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[a-zA-Z]{2} any character of: 'a' to 'z', 'A' to 'Z'
(2 times)
----------------------------------------------------------------------
\d{6} digits (0-9) (6 times)
----------------------------------------------------------------------
[a-zA-Z]? any character of: 'a' to 'z', 'A' to 'Z'
(optional (matching the most amount
possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\d{9} digits (0-9) (9 times)
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------