在Ruby中检查包含字母数字的字符串的正则表达式

18

我正在尝试在Ruby中验证字符串。 任何包含空格、下划线或任何特殊字符的字符串都应该验证失败。 有效字符串只能包含a-zA-Z0-9这些字符。 我的代码看起来像这样。

def validate(string)
    regex ="/[^a-zA-Z0-9]$/
    if(string =~ regex)
        return "true"
    else
        return "false"
end
我遇到了错误: TypeError: 类型不匹配,应该是字符串类型。
请问有没有人能告诉我正确的做法?

请查看http://ideone.com/TKD3QW - Wiktor Stribiżew
只包含字符a-zA-Z0-9。可能是这个正则表达式:/^[a-zA-Z0-9]+$/ - user557597
2
@sln:在Ruby正则表达式中,“^”和“$”的含义与您想象的不同,您几乎总是需要使用“\A”和“\z”。 - mu is too short
@muistooshort - 啊,Ruby是个古怪的家伙。是的,那么就用\A\z吧。 - user557597
1
你可以使用\w来代替[a-zA-Z0-9],作为一种快捷方式。顺便说一下。 - frosty
3
@frosty: \w 同样匹配 _(下划线)。 - cremno
8个回答

14

如果您正在验证一行:

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

每个都不需要回车。


5

您可以检查字符串中是否存在特殊字符。

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

4
我建议使用str.chars.all? {|ch| chars.include?(ch)}(更易读)。同时,使用chars作为变量名和方法chars可能会造成混淆。最好避免使用与方法同名的变量名。 - Cary Swoveland

5
def alpha_numeric?(char)  
 
   if (char =~ /[[:alpha:]]/ || char =~ /[[:digit:]]/)
      true
   else
      false
   end

end

或者

def alpha_numeric?(char)  
 
   if (char =~ /[[:alnum:]]/)
      true
   else
      false
   end

end

我们正在使用匹配字母和数字的正则表达式:
上述[[:alpha:]]、[[:digit:]]和[[:alnum:]]是POSIX括号表达式,它们具有匹配其类别中的Unicode字符的优点。希望这可以帮助您。
查看以下链接获取更多选项: Ruby:如何确定字符是字母还是数字?

1

没有正则表达式:

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

有趣的是,除了一个答案外,所有答案都收到了负评。我今天也收到了我的。 - Cary Swoveland
有点奇怪说不使用正则表达式,因为你正在传递一个正则表达式。 - drewish
@drewish 当然,它们很相似。有效的正则表达式应该是 /[^a-zA-Z0-9]/(就像 Joshua Pinter 的答案中所示)。 - steenslag
不,我错了。我以为 count 方法只是将传入的正则表达式的字符串版本转换为正则表达式。看了文档后,我明白了你的观点,它们使用相同的字符类语法,但它并不是完整的正则表达式。 - drewish

1

与@steenslag提到的非常高效的正则表达式方法类似,几乎同样快:

str.tr("a-zA-Z0-9", "").length.zero?

或者

str.tr("a-zA-Z0-9", "") == 0
< p > 使用 tr 的一个好处是,您还可以使用相同的基本公式选择性地分析结果:

str = "ABCxyz*123$"

rejected_chars = str.tr("a-zA-Z0-9", "")
#=>  *$

is_valid = rejected_chars.length.zero?
#=> false

1
上面的回答很棒,但是提醒一下,你的错误信息是因为你在正则表达式开头使用了双引号"。你会发现你的方法中有奇数(5)个双引号。
此外,你可能想要将true和false作为值返回,而不是作为带引号的字符串。

0

类似于 @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

使用 Ruby 2.4+ 中的 .match? 方法。

Ruby 2.4 引入了一个方便的布尔值返回的 .match? 方法。

在您的情况下,我会这样做:

# Checks for any characters other than letters and numbers.
# Returns true if there are none. Returns false if there are one or more.
#
def valid?( string )
  !string.match?( /[^a-zA-Z0-9]/ ) # NOTE: ^ inside [] set turns it into a negated set.
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接