Regex to check alphanumeric string in ruby

前端 未结 6 1932
生来不讨喜
生来不讨喜 2021-02-19 21:40

I am trying to validate strings in ruby. Any string which contains spaces,under scores or any special char should fail validation. The valid string should contain only chars a-z

6条回答
  •  猫巷女王i
    2021-02-19 22:07

    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
    

    Result:

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

提交回复
热议问题