Ruby:如何确定字符是字母还是数字?

Cor*_*gan 22 ruby string character digits

本周早些时候我刚开始修改Ruby,我遇到了一些我不太懂的代码.我正在将用Java编写的扫描程序转换为Ruby以进行类分配,我已经深入到本节:

if (Character.isLetter(lookAhead))
{      
    return id();
}

if (Character.isDigit(lookAhead))
{
    return number();
}
Run Code Online (Sandbox Code Playgroud)

lookAhead是从字符串中挑出的单个字符(每次循环时移动一个空格),这两个方法确定它是字符还是数字,返回相应的标记类型.我一直没能到一个Ruby相当于找出该Character.isLetter()Character.isDigit().

And*_*all 44

使用与字母和数字匹配的正则表达式:

def letter?(lookAhead)
  lookAhead =~ /[[:alpha:]]/
end

def numeric?(lookAhead)
  lookAhead =~ /[[:digit:]]/
end
Run Code Online (Sandbox Code Playgroud)

这些被称为POSIX括号表达式,它们的优点是给定类别下的unicode字符将匹配.例如:

'ñ' =~ /[A-Za-z]/    #=> nil
'ñ' =~ /\w/          #=> nil
'ñ' =~ /[[:alpha:]]/   #=> 0
Run Code Online (Sandbox Code Playgroud)

您可以在Ruby的正则表达式文档中阅读更多内容.

  • `lookAhead =~ /[[:alnum:]]/` 如果你只想检查字符是否是字母数字而不需要知道是哪个。 (2认同)

Pin*_*nyM 13

最简单的方法是使用正则表达式:

def numeric?(lookAhead)
  lookAhead =~ /[0-9]/
end

def letter?(lookAhead)
  lookAhead =~ /[A-Za-z]/
end
Run Code Online (Sandbox Code Playgroud)

  • `/ [[:digit:]] /`比`/ [0-9] /`&`/ [[:alpha:]] /`好于`/ [A-Za-z] /`.这将匹配unicode数字/字母. (3认同)
  • 这是损坏的:`letter?('Ä') # => false`。 (2认同)

Ale*_*der 6

正则表达式在这里是一种杀伤力,它在性能方面要昂贵得多。如果您只需要检查字符是否为数字,则有一种更简单的方法:

def is_digit?(s)
  code = s.ord
  # 48 is ASCII code of 0
  # 57 is ASCII code of 9
  48 <= code && code <= 57
end

is_digit?("2")
=> true

is_digit?("0")
=> true

is_digit?("9")
=> true

is_digit?("/")
=> false

is_digit?("d")
=> false
Run Code Online (Sandbox Code Playgroud)