Check non-numeric characters in string

后端 未结 2 1166
有刺的猬
有刺的猬 2020-12-17 01:52

I want to check whether the String contains only numeric characters or it contains alpha-numeric characters too.

I have to implement this check in database transacti

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 02:23

    Just Googling, I found out this link

     public boolean containsOnlyNumbers(String str) {        
            //It can't contain only numbers if it's null or empty...
            if (str == null || str.length() == 0)
                return false;
    
            for (int i = 0; i < str.length(); i++) {
    
                //If we find a non-digit character we return false.
                if (!Character.isDigit(str.charAt(i)))
                    return false;
            }
    
            return true;
        }
    

    Edit: A RegExp to check numeric should be :

    return yourNumber.matches("-?\\d+(.\\d+)?");
    

提交回复
热议问题