在Ruby中,你可以使用正則表達式來驗證字符串的格式。正則表達式是一種描述字符串模式的強大工具,可以幫助你檢查字符串是否符合預(yù)期的格式。以下是一些常見的字符串格式驗證示例:
email = "example@example.com"
pattern = /\A[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\z/
if pattern.match?(email)
puts "Valid email"
else
puts "Invalid email"
end
phone = "123-456-7890"
pattern = /\A(\d{3})-(\d{3})-(\d{4})\z/
if pattern.match?(phone)
puts "Valid phone number"
else
puts "Invalid phone number"
end
url = "https://www.example.com"
pattern = /\Ahttps:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\/?\z/
if pattern.match?(url)
puts "Valid URL"
else
puts "Invalid URL"
end
password = "Example@123#"
pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
if pattern.match?(password)
puts "Valid password"
else
puts "Invalid password"
end
你可以根據(jù)需要修改正則表達式以匹配特定的字符串格式。如果字符串與正則表達式匹配,match?
方法將返回true
,否則返回false
。