Regex to check alphanumeric string in ruby

def alpha_numeric?(char)  
 
   if((char =~ /[[:alpha:]]) || (char =~ [[:digits:]]))
      true
   else
      false
   end

end

OR

def alpha_numeric?(char)  
 
   if(char =~ /[[:alnum:]])
      true
   else
      false
   end

end

We are using regular expressions that match letters & digits:

The above [[:alpha:]] ,[[:digit:]] and [[:alnum:]] are POSIX bracket expressions, and they have the advantage of matching Unicode characters in their category. Hope this helps.

checkout the link below for more options: Ruby: How to find out if a character is a letter or a digit?


If you are validating a line:

def validate(string)
  !string.match(/\A[a-zA-Z0-9]*\z/).nil?
end

No need for return on each.


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