Ruby:如何确定一个字符是字母还是数字? [英] Ruby: How to find out if a character is a letter or a digit?
问题描述
本周早些时候,我刚刚开始尝试Ruby,但遇到了一些我不太会编码的事情。我正在将用Java编写的扫描仪转换为Ruby以进行类分配,并且我已经深入到本节:
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:
if (Character.isLetter(lookAhead))
{
return id();
}
if (Character.isDigit(lookAhead))
{
return number();
}
lookAhead
是从字符串中选出一个字符(每次循环时移动一个空格),这两种方法确定它是字符还是数字,并返回适当的标记类型。我还无法找出与 Character.isLetter()
和 Character.isDigit()
等价的Ruby。 。
lookAhead
is 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()
.
推荐答案
使用与字母&匹配的正则表达式数字:
Use a regular expression that matches letters & digits:
def letter?(lookAhead)
lookAhead =~ /[[:alpha:]]/
end
def numeric?(lookAhead)
lookAhead =~ /[[:digit:]]/
end
这些被称为POSIX括号表达式,它们的优点是给定类别下的unicode字符将匹配。例如:
These are called POSIX bracket expressions, and the advantage of them is that unicode characters under the given category will match. For example:
'ñ' =~ /[A-Za-z]/ #=> nil
'ñ' =~ /\w/ #=> nil
'ñ' =~ /[[:alpha:]]/ #=> 0
您可以在 Ruby的正则表达式文档。
这篇关于Ruby:如何确定一个字符是字母还是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!