Regex to check alphanumeric string in ruby

前端 未结 6 2023
生来不讨喜
生来不讨喜 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条回答
  •  青春惊慌失措
    2021-02-19 22:16

    Similar to @rohit89:

    VALID_CHARS = [*?a..?z, *?A..?Z, *'0'..'9']
      #=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
      #    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
      #    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
      #    "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
      #    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
    def all_valid_chars?(str)
      a = str.chars
      a == a & VALID_CHARS
    end
    
    all_valid_chars?('a9Z3')  #=> true
    all_valid_chars?('a9 Z3') #=> false
    

提交回复
热议问题