check if a string contains only alphanumeric characters in Ruby
Code snippet on how to check if a string contains only alphanumeric characters in Ruby
def checkString(str)
str.match(/\A[a-zA-Z0-9]*\z/)
end
This code checks if a string contains only alphanumeric characters (which includes all letters and numbers). The start of the string is indicated with \A and the end of the string with \z, which means only characters between those two symbols will be evaluated. The range between a-z, A-Z, and 0-9 means that only characters in those ranges are considered valid. The * at the end indicates any number of characters, meaning that even if the string is empty, it can still be considered valid. The match() method checks if the input string matches the regex pattern, which in this case is the range of characters between \A and \z. If the input string only contains characters within the given range, it will return true.