试试这个。
def get_password
loop do
puts "Please enter your password"
my_password = gets.chomp
str =
case my_password
when /\A.{,6}\z/ then "seven characters"
when /\A[^A-Z]+\z/ then "one uppercase letter"
when /\A[^a-z]+\z/ then "one lowercase letter"
when /\A\D+\z/ then "one digit"
when /\A[^$%&!]+\z/ then "one symbol"
else break my_password
end
puts "Passwords must contain at least #{str}"
end
end
pw = get_password
#=> "abcDEF123$$$"
puts pw
"abcDEF123$$$"
请注意,在获得有效密码之前,该方法不会返回。什么是允许的符号当然必须定义。
如果要显示一个值,通常最好从方法中返回该值,然后显示它。这样,可以使用相同的方法来获取要以其他方式使用的密码,而不仅仅是显示它。
也可以这样写。
R = /
\A
(?=.{7}) # match seven chars in a positive lookahead
(?=.*\p{Ll}) # match a lowercase letter in a positive lookahead
(?=.*\p{Lu}) # match an uppercase letter in a positive lookahead
(?=.*\d) # match a digit in a positive lookahead
(?=.*[$%&!]) # match a symbol in a positive lookahead
/x # free-spacing regex definition mode
def get_password
loop do
puts "Please enter your password"
my_password = gets.chomp
break my_password if my_password.match?(R)
puts "Passwords must contain at least seven characters, one uppercase"
puts "letter, one lowercase letter and one symbol"
end
end
pw = get_password
#=> "aA1$$$$$$$$$$$$$$$$$$$$"
正则表达式通常写成如下。
R = /\A\(?=.{7})(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\d)(?=.*[$%&!])/