我正在尝试验证具有以下规则的UID
- 它必须至少包含2个大写英文字母字符
- 它必须至少包含3个数字(0-9(
- 它应该只包含字母数字字符
- 任何字符都不应重复
- 有效的UID中必须正好有10个字符
我尝试过用正则表达式来做,但我无法创建一个满足所有规则的模式。
所以我没有使用正则表达式。
#import re
#pattern = r'^[A-Z0-9]{10}$'
testCases = int(input())
for _ in range(testCases):
uid = input()
if len(uid) == 10 and len(uid) == len(set(uid)):
countChr = countNum = 0
for i in uid:
if i.isdigit():
countNum += 1
elif i.isalpha():
countChr +=1
if countChr >= 2 and countNum >= 3:
print("Valid")
else:
print("Invalid")
else:
print("Invalid")
上面的程序运行得很好,但我想用正则表达式验证UID,那么有什么模式可以满足所有给定的规则吗?
试试这个正则表达式:
^(?=(?:.*[A-Z]){2})(?=(?:.*[0-9]){3})(?:([a-zA-Z0-9])(?!.*1)){10}$
^ beginning of the text
(?= positive lookahead
(?: non-capturing group
.*[A-Z] anything followed by an uppercased letter
){2} match 2 of them
) end of the lookahead
(?= positive lookahead
(?: non-capturing group
.*[0-9] anything followed by a digit
){3} match 3 of them
) end of the lookahead
(?: non-capturing group
([a-zA-Z0-9]) any alphanumeric character and put it in group 1
(?!.*1) negative lookahead, make sure there's no repeated character ahead
){10} match 10 of them
$ end of the text
检查测试用例
使用python
import re
pattern = r'^(?=(?:.*[A-Z]){2})(?=(?:.*[0-9]){3})(?:([a-zA-Z0-9])(?!.*1)){10}$'
testCases = int(input())
for _ in range(testCases):
uid = input()
if re.match(pattern, uid):
print("Valid")
else:
print("Invalid")
let regex = /^(?!.*?(.).*?1)(?=(?:.*?[A-Z]){2,})(?=(?:.*?d){3,})[a-zA-Zd]{10}$/;
console.log(regex.test("A0ieu5Wsl2"));
console.log(regex.test("A0ieuiWsl2"));
console.log(regex.test("A0ieu5Wsl2l"));