且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式检查 ruby​​ 中的字母数字字符串

更新时间:2023-02-26 13:52:33

您可以只检查字符串中是否存在特殊字符.

You can just check if a special character is present in the string.

def validate str
 chars = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
 str.chars.detect {|ch| !chars.include?(ch)}.nil?
end

结果:

irb(main):005:0> validate "hello"
=> true
irb(main):006:0> validate "_90 "
=> false