我想确保用户输入的密码长度至少为7个字符,并且至少包含一个大写字母,一个小写字母,一个数字和一个符号。 代码似乎通过if循环直到它被卡住的符号参数。
puts "Please enter your desired password: "
password = []
pass_clear = ()
while pass_clear == (nil) do
password = gets.to_s.chomp
if password.length < 7
puts "Your password must contain at least seven characters."
elsif password.count("a-z") == password.length
puts "Your password must contain at least one uppercase character."
elsif password.count("A-Z") == password.length
puts "Your password must contain at least one lowercase character."
elsif password.count("!","@","#","$","%","^","&","*","(",")","_","-","+","=") < 1
puts "Your password must contain at least one symbol."
elsif password.count("0","1","2","3","4","5","6","7","8","9") < 1
puts "Your password must contain at least one number."
else
puts "Thank you, your account is complete."
pass_clear == 1
end
end
这是输出:
Please enter your desired password:
frank
Your password must contain at least seven characters.
Please enter your desired password:
frankie
Your password must contain at least one uppercase character.
Please enter your desired password:
Frankie
Your password must contain at least one symbol.
Please enter your desired password:
Frankie$
Your password must contain at least one symbol.
Please enter your desired password:
无论有多少符号,它都会继续循环遍历符号阶段。 如何确保识别这些符号以便循环完成?
答案 0 :(得分:2)
您引用的每个符号都不正确。你还必须逃避 - 和^字符
password.count("!@#$%\\^&*()_\\-+=")
在这个例子中,对我有用。
您还需要为您的数字使用范围,例如:
password.count("0-9")
- 字符用于&#34; a-z&#34;等范围。所以它必须被转义,carat ^用于否定计数,所以:
password.count(&#34; ^ A-Z&#34)
将返回a-z范围内不包含的所有内容的计数。
这可以派上用场,因为您可能希望阻止某些字符出现在您的密码字符串中。你可以这样做:
password.count("^a-zA-Z!@#$%\\^&*()_\\-+=0-9)
这将计算您已定义的所有其他字符,因此您希望获得零返回值,以便知道它们没有使用任何禁用字符。
进一步澄清count()
中的范围。术语&#34;范围&#34;不应该与Ruby类&#34; Range&#34;混淆。 Range类使用&#34; ..&#34;或&#34; ...&#34;介入项目。在count()
方法中,考虑的范围是从第一个字符的ASCII号到第二个字符的ASCII号的ASCII范围。这就是为什么在A-z
的原始错字中,它将ASCII 65(&#34; A&#34;)计算为ASCII 122(&#34; z&#34;),其恰好包括字符ASCII 92到96不是字母而是\] ^ _`
答案 1 :(得分:0)
一种选择是使用包含四个正向前瞻的正则表达式,所有这些都在字符串的开头操作。
R = /
(?=.*\p{Ll}) # match lowercase letter
(?=.*\p{Lu}) # match uppercase letter
(?=.*\d) # match digit
(?=.*[#{Regexp.escape("!@#$%^&*(,)_+=-")}]) # match special char
/x # free-spacing regex def mode
def password_ok?(str)
str.match?(R)
end
password_ok? "aA1#" #=> true
password_ok? "A1#" #=> false
password_ok? "a1#" #=> false
password_ok? "aA#" #=> false
password_ok? "aA1" #=> false