A regular expression for checking an alphanumeric string in a ruby

I am trying to check strings in ruby. Any line containing spaces under the banners or some special char should fail validation. A valid string should contain only characters a-zA-Z0-9 My code looks.

def validate(string) regex ="/[^a-zA-Z0-9]$/ if(string =~ regex) return "true" else return "false" end 

I get the error: TypeError: type mismatch: specified string.

Can someone please let me know what is the right way to do this?

+6
source share
5 answers

You can simply 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 
+3
source

If you check the line:

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

No need to return to everyone.

+3
source

Similar to @ rohit89:

 VALID_CHARS = [*?a..?z, *?A..?Z, *'0'..'9'] #=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", # "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", # "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", # "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", # "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] def all_valid_chars?(str) a = str.chars a == a & VALID_CHARS end all_valid_chars?('a9Z3') #=> true all_valid_chars?('a9 Z3') #=> false 
0
source

No regex:

 def validate(str) str.count("^a-zA-Z0-9").zero? # ^ means "not" end 
0
source

The excellent answers are above, but only FYI, your error message is because you started the regular expression with a double quote. " You will notice that you have an odd number (5) of double quotes in your method.

In addition, most likely you want to return true and false as values, and not as quoted strings.

0
source

All Articles