问题
在Java中有一种方法可以找出字符串的第一个字符是否为数字?
一种方法是
string.startsWith("1")
直到9点一直做到这一点,但这似乎效率很低。
#1 热门回答(251 赞)
Character.isDigit(string.charAt(0))
请注意,这将允许任何数字,而不仅仅是0-9。你可能更喜欢:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
或者较慢的正则表达式解决方案:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
但是,使用这些方法中的任何一种,必须首先确保该字符串不为空。如果是,charAt(0)
和substring(0, 1)
将抛出aStringIndexOutOfBoundsException
.startsWith
没有这个问题。
要使整个条件成一行并避免长度检查,可以将正则表达式更改为以下内容:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
如果条件没有出现在程序的紧密循环中,那么使用正则表达式的性能影响不大可能会很明显。
#2 热门回答(8 赞)
正则表达式是非常强大但昂贵的工具。使用它们来检查第一个字符是否是数字是有效的但它不是那么优雅:)我更喜欢这样:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
#3 热门回答(0 赞)
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}