检查字符串是否为数字

时间:2015-06-28 15:46:16

标签: java regex

我正在尝试检查字符串是否为数字。我尝试过以下内容,它分开工作但不能一起工作。

if (i.matches("\\d{2} | [0-9]"))

我感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我认为您正在尝试检查给定字符串是否为一位或两位数字。

if (i.matches("\\d{1,2}"))

请注意,matches方法不需要锚点。它会进行精确的字符串匹配。

答案 1 :(得分:0)

您可以使用Java提供的异常机制来解决此问题。

如果提供的字符串不是有效的十进制数,则类BigInteger的构造函数BigInteger(String val)会抛出NumberFormatException

public static boolean isNumber(String string) {
    if (string != null) {
        try {
            new BigInteger(string);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }
    return false;
}

您还可以使用类BigInteger - BigInteger(String val, int radix)的其他构造函数来检查提供的字符串是否为基数为radix的数字。

例如:76576ACFED65是基数为16的有效数字。

相关问题