Joã*_*lva 7

紧凑型版本,使用正向前瞻操作符:

^(?=(.*[0-9]){2})(?=(.*[A-Za-z]){4})[A-Za-z0-9]{6}$
Run Code Online (Sandbox Code Playgroud)

说明:

(?=(.*[0-9]){2}) # asserts that you have 2 digits
(?=(.*[A-Za-z]){4}) # asserts that you have 4 characters
[A-Za-z0-9]{6} # does the actual matching of exactly 6 alphanumeric characters
Run Code Online (Sandbox Code Playgroud)

一个简单的测试用例,在Python中:

import re
rex = re.compile('(?=(.*[0-9]){2})(?=(.*[A-Za-z]){4})[A-Za-z0-9]{6}')
tests = ['aBCd22', 'a2b2CD', '22aBcD', 'asd2as', '', '201ABC', 'abcA213']
for test in tests:
print "'%s' %s" % 
       (test, "matched" if rex.match(test) != None else "didn't match")
Run Code Online (Sandbox Code Playgroud)

输出:

'aBCd22' matched
'a2b2CD' matched
'22aBcD' matched
'asdas' didn't match
'' didn't match
'201ABC' didn't match
'abcA213' didn't match
Run Code Online (Sandbox Code Playgroud)