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?
You can just use \w for any [a-zA-Z0-9], as a shortcut, btw.
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
Regular expressions (regexps) are patterns which describe the contents of a string. They're used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the / pat / and %r{ pat } literals or the Regexp.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With