Java库来检查一个字符串是否包含一个数字*无*异常 [英] Java library to check whether a String contains a number *without* exceptions

查看:181
本文介绍了Java库来检查一个字符串是否包含一个数字*无*异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个方法返回一个布尔值,如果它传递的字符串是一个有效的数字(例如123.55e-9,-333,556)。

  public boolean isANumber(String s){
尝试{
BigDecimal a = new BigDecimal(s);
返回true;
} catch(NumberFormatException e){
return false;






$ b显然,函数应该使用状态机(DFA )来解析字符串以确保无效示例不会愚弄它(例如-21,22.22.2,33-2)。你知道有这样的图书馆吗?我真的不想自己写,因为这是一个明显的问题,我确信我会重新发明轮子。



谢谢, p>

Nick

解决方案

我会避免重新发明这个方法, Apache Commons。如果你使用Spring,Struts或者其他常用的java库,他们通常会包含Apache commons。你将需要commons-lang.jar文件。以下是 NumberUtils 你想要的:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ public static boolean isNumber(java.lang.String str)
检查String是否为有效的Java编号。

有效数字包括标有0x限定符的十六进制数,科学记数法和标有类型限定符(例如123L)的数字。

空字符串将返回false。

参数:
str - 要检查的字符串
返回:
如果字符串格式正确,则为true


I'm looking for a method that returns a boolean if the String it is passed is a valid number (e.g. "123.55e-9", "-333,556"). I don't want to just do:

public boolean isANumber(String s) {
    try { 
        BigDecimal a = new BigDecimal(s); 
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Clearly, the function should use a state machine (DFA) to parse the string to make sure invalid examples don't fool it (e.g. "-21,22.22.2", "33-2"). Do you know if any such library exists? I don't really want to write it myself as it's such an obvious problem that I'm sure I'd be re-inventing the wheel.

Thanks,

Nick

解决方案

I would avoid re-inventing this method and go with Apache Commons. If your using Spring, Struts or many other commonly used java libraries, they often have Apache commons included. You will want the commons-lang.jar file. Here is the method in NumberUtils you would want:

isNumber[1]

public static boolean isNumber(java.lang.String str)
Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).

Null and empty String will return false.

Parameters:
str - the String to check
Returns:
true if the string is a correctly formatted number

这篇关于Java库来检查一个字符串是否包含一个数字*无*异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆