检测字符串是否为数字的最优雅方法?
有没有比
boolean isNumber = false;
try{
Double.valueOf(myNumber);
isNumber = true;
} catch (NumberFormatException e) {
}
...?
编辑:由于我无法选择两个答案,我将使用正则表达式一个,因为 a) 它很优雅 b) 说Jon Skeet 解决了问题"是重言式,因为 Jon Skeet 自己是所有问题的解决方案.
Edit: Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems.
推荐答案
我不相信 Java 中内置了任何东西可以更快、更可靠地完成它,假设稍后你会想用 Double 实际解析它.valueOf(或类似).
I don't believe there's anything built into Java to do it faster and still reliably, assuming that later on you'll want to actually parse it with Double.valueOf (or similar).
我会使用 Double.parseDouble 而不是 Double.valueOf 来避免不必要地创建 Double,并且您还可以通过检查数字来比异常更快地摆脱明显愚蠢的数字,e/E, - 和 .预先.所以,类似:
I'd use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, and you can also get rid of blatantly silly numbers quicker than the exception will by checking for digits, e/E, - and . beforehand. So, something like:
public boolean isDouble(String value)
{
boolean seenDot = false;
boolean seenExp = false;
boolean justSeenExp = false;
boolean seenDigit = false;
for (int i=0; i < value.length(); i++)
{
char c = value.charAt(i);
if (c >= '0' && c <= '9')
{
seenDigit = true;
continue;
}
if ((c == '-' || c=='+') && (i == 0 || justSeenExp))
{
continue;
}
if (c == '.' && !seenDot)
{
seenDot = true;
continue;
}
justSeenExp = false;
if ((c == 'e' || c == 'E') && !seenExp)
{
seenExp = true;
justSeenExp = true;
continue;
}
return false;
}
if (!seenDigit)
{
return false;
}
try
{
Double.parseDouble(value);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
请注意,尽管尝试了几次,这仍然不包括NaN"或十六进制值.您是否希望这些通过取决于上下文.
Note that despite taking a couple of tries, this still doesn't cover "NaN" or hex values. Whether you want those to pass or not depends on context.
根据我的经验,正则表达式比上面的硬编码检查要慢.
In my experience regular expressions are slower than the hard-coded check above.
相关文章