正则表达式检查 ruby 中的字母数字字符串 [英] Regex to check alphanumeric string in ruby
本文介绍了正则表达式检查 ruby 中的字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试验证 ruby 中的字符串.任何包含空格、下划线或任何特殊字符的字符串都应无法通过验证.有效字符串应仅包含字符 a-zA-Z0-9我的代码看起来像.
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 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
结果:
irb(main):005:0> validate "hello"
=> true
irb(main):006:0> validate "_90 "
=> false
这篇关于正则表达式检查 ruby 中的字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文