我的理解是您希望确认一个字符串包含,以任何顺序:
- 2 个小写字母
- 2 个大写字母
- 2 位数
- 1(指定)“特殊”字符和
- 1 到 3 个附加字符(可能包括字母、数字和特殊字符)
这里有几种方法。
排序后使用正则表达式
代码
def confirm(str, special)
r = /
[A-Z]{2,} # match at least 2 uppercase letters
[a-z]{2,} # match at least 2 lowercase letters
\d{2,} # match at least 2 digits
#{special} # match the special character
/x # free-spacing regex definition mode
str.size.between?(8,10) && str.each_char.sort_by do |c|
case c
when /[A-Z]/ then 0
when /[a-z]/ then 1
when /\d+/ then 2
when special then 3
else 4
end
end.join =~ r ? true : false
end
例子
confirm("aaAA12%%", "%") #=> true
confirm("aAaA%3%3", "%") #=> true
confirm("2aAaA%3%3", "%") #=> true
confirm("2aA1bA%A%3", "%") #=> true
confirm("2aA1bA%4%3", "%") #=> true
confirm("aAaaA%3a%3", "%") #=> true
confirm("2aAaA%3%3", "%") #=> true
confirm("aaA12%4%", "%") #=> false
confirm("aAA12%4%", "%") #=> false
confirm("aaAA1%aa%", "%") #=> false
confirm("2aA1b4A%3%3", "%") #=> false
confirm("aA1bA%3", "%") #=> false
计算字符数
代码
def confirm(str, special)
str.size.between?(8,10) && str.scan(/[A-Z]/).size >= 2 &&
str.scan(/[a-z]/).size >= 2 && str.scan(/\d/).size >= 2 &&
str.count(special) >= 1
end
例子
confirm("aaAA12%%", "%") #=> true
confirm("aAaA%3%3", "%") #=> true
confirm("2aAaA%3%3", "%") #=> true
confirm("2aA1bA%A%3", "%") #=> true
confirm("2aA1bA%4%3", "%") #=> true
confirm("aAaaA%3a%3", "%") #=> true
confirm("2aAaA%3%3", "%") #=> true
confirm("aaA12%4%", "%") #=> false
confirm("aAA12%4%", "%") #=> false
confirm("aaAA1%aa%", "%") #=> false
confirm("2aA1b4A%3%3", "%") #=> false
confirm("aA1bA%3", "%") #=> false