这周早些时候,我刚刚开始使用Ruby,我遇到了一些我不太知道如何编码的东西。我正在将一个用Java编写的扫描器转换为Ruby,以便进行类赋值,我已经深入到这一部分:
if (Character.isLetter(lookAhead))
{
return id();
}
if (Character.isDigit(lookAhead))
{
return number();
}
lookAhead
是从字符串中挑选出的单个字符(每次循环时移动一个空格),这两个方法确定它是字符还是数字,并返回适当的标记类型。我还没能想出一个与Character.isLetter()
和Character.isDigit()
相当的Ruby。
发布于 2013-01-28 04:36:51
使用与字母和数字匹配的正则表达式:
def letter?(lookAhead)
lookAhead.match?(/[[:alpha:]]/)
end
def numeric?(lookAhead)
lookAhead.match?(/[[:digit:]]/)
end
这些表达式称为POSIX括号表达式,它们的优点是给定类别下的unicode字符将匹配。例如:
'ñ'.match?(/[A-Za-z]/) #=> false
'ñ'.match?(/\w/) #=> false
'ñ'.match?(/[[:alpha:]]/) #=> true
您可以在Ruby’s docs for regular expressions中阅读更多内容。
发布于 2013-01-28 03:30:50
最简单的方法是使用正则表达式:
def numeric?(lookAhead)
lookAhead =~ /[0-9]/
end
def letter?(lookAhead)
lookAhead =~ /[A-Za-z]/
end
发布于 2021-01-27 04:16:44
正则表达式在这里有点夸张,它在性能方面要昂贵得多。如果您只需要检查字符是数字还是不是,有一种更简单的方法:
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
https://stackoverflow.com/questions/14551256
复制相似问题