简体   繁体   English

检查字符串是否为数字

[英]Check whether a string is a number

I am trying to check whether a string is a number. 我正在尝试检查字符串是否为数字。 I have tried the following, which works separately but not together. 我尝试了以下方法,它们可以分开但不能一起工作。

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

I appreciate any help. 感谢您的帮助。

I think you're trying to check whether the given string is a one or two digit number or not. 我认为您正在尝试检查给定的字符串是一位数还是两位数。

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

Note that matches method won't need anchors. 请注意, matches方法不需要锚点。 It would do an exact string match. 它将进行精确的字符串匹配。

You can use Exception mechanism to provided by Java to address this problem. 您可以使用Java提供的Exception机制来解决此问题。

The constructor BigInteger(String val) of class BigInteger throws NumberFormatException if the provided string is not a valid decimal number. 如果提供的字符串不是有效的十进制数字,则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;
}

You can also use another constructor of class BigInteger - BigInteger(String val, int radix) to check whether the provided string is a number with base radix . 您还可以使用BigInteger类的另一个构造函数BigInteger(String val, int radix)检查所提供的字符串是否为具有radix的数字。

Eg: 76576ACFED65 is a valid number with base 16. 例如:76576ACFED65是以16为底的有效数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM