Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check alphanumeric string in ruby

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?

like image 745
Mandar Dalvi Avatar asked Oct 21 '15 18:10

Mandar Dalvi


People also ask

How do I check if a string is alphanumeric Ruby?

You can just use \w for any [a-zA-Z0-9], as a shortcut, btw.

What does =~ mean in Ruby?

=~ 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.

What is Regexp ruby?

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.


1 Answers

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?

like image 54
Enow B. Mbi Avatar answered Sep 17 '22 17:09

Enow B. Mbi