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-zA-Z0-9 My code looks like.
def validate(string)
regex ="/[^a-zA-Z0-9]$/
if(string =~ regex)
return "true"
else
return "false"
end
I am getting error: TypeError: type mismatch: String given.
Can anyone please let me know what is the correct way of doing this?
No regex:
If you are validating a line:
No need for return on each.
You can just check if a special character is present in the string.
Result:
OR
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 helps.
checkout the link below for more options: Ruby: How to find out if a character is a letter or a digit?
Great answers above but just FYI, your error message is because you started your regex with a double quote
"
. You'll notice you have an odd number (5) of double quotes in your method.Additionally, it's likely you want to return true and false as values rather than as quoted strings.
Similar to @rohit89: