Ruby:如何确定一个字符是字母还是数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14551256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: How to find out if a character is a letter or a digit?
提问by Cory Regan
I just started tinkering with Ruby earlier this week and I've run into something that I don't quite know how to code. I'm converting a scanner that was written in Java into Ruby for a class assignment, and I've gotten down to this section:
本周早些时候我刚刚开始修补 Ruby,但遇到了一些我不太了解如何编码的问题。我正在将用 Java 编写的扫描仪转换为 Ruby 以进行类分配,并且我已经进入了这一部分:
if (Character.isLetter(lookAhead))
{
return id();
}
if (Character.isDigit(lookAhead))
{
return number();
}
lookAheadis a single character picked out of the string (moving by one space each time it loops through) and these two methods determine if it is a character or a digit, returning the appropriate token type. I haven't been able to figure out a Ruby equivalent to Character.isLetter()and Character.isDigit().
lookAhead是从字符串中选出的单个字符(每次循环时移动一个空格),这两种方法确定它是字符还是数字,返回适当的标记类型。我一直无法找出与Character.isLetter()和等价的 Ruby Character.isDigit()。
回答by Andrew Marshall
Use a regular expression that matches letters & digits:
使用匹配字母和数字的正则表达式:
def letter?(lookAhead)
lookAhead =~ /[[:alpha:]]/
end
def numeric?(lookAhead)
lookAhead =~ /[[:digit:]]/
end
These are called POSIX bracket expressions, and the advantage of them is that unicode characters under the given category will match. For example:
这些被称为 POSIX 括号表达式,它们的优点是给定类别下的 unicode 字符将匹配。例如:
'?' =~ /[A-Za-z]/ #=> nil
'?' =~ /\w/ #=> nil
'?' =~ /[[:alpha:]]/ #=> 0
You can read more in Ruby's docs for regular expressions.
您可以在Ruby 的正则表达式文档中阅读更多内容。
回答by PinnyM
The simplest way would be to use a Regular Expression:
最简单的方法是使用正则表达式:
def numeric?(lookAhead)
lookAhead =~ /[0-9]/
end
def letter?(lookAhead)
lookAhead =~ /[A-Za-z]/
end

