Regex to check alphanumeric string in ruby

2020-07-06 05:36发布

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?

6条回答
Bombasti
2楼-- · 2020-07-06 06:15

No regex:

def validate(str)
  str.count("^a-zA-Z0-9").zero?  # ^ means "not"
end
查看更多
smile是对你的礼貌
3楼-- · 2020-07-06 06:21

If you are validating a line:

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

No need for return on each.

查看更多
在下西门庆
4楼-- · 2020-07-06 06:23

You can just 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
查看更多
走好不送
5楼-- · 2020-07-06 06:26
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 helps.

checkout the link below for more options: Ruby: How to find out if a character is a letter or a digit?

查看更多
The star\"
6楼-- · 2020-07-06 06:29

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.

查看更多
SAY GOODBYE
7楼-- · 2020-07-06 06:36

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
查看更多
登录 后发表回答