java - Long.valueOf(workOrder.getCreator())类型验证
天蓬老师
天蓬老师 2017-04-18 09:21:37
0
1
879
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(1)
黄舟
public static boolean isNumeric(String str) {
        if (null == str) {
            return false;
        }

        int length = str.length();

        for (int i = 0; i < length; i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

public boolean isNumeric(String str){ 
   Pattern pattern = Pattern.compile("[0-9]*"); 
   Matcher isNum = pattern.matcher(str);
   if( !isNum.matches() ){
       return false; 
   } 
   return true; 
}

使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
 StringUtils.isNumeric(null)   = false
 StringUtils.isNumeric("")     = true
 StringUtils.isNumeric("  ")   = false
 StringUtils.isNumeric("123")  = true
 StringUtils.isNumeric("12 3") = false
 StringUtils.isNumeric("ab2c") = false
 StringUtils.isNumeric("12-3") = false
 StringUtils.isNumeric("12.3") = false
 
Parameters:
str - the String to check, may be null 
Returns:
true if only contains digits, and is non-null

上面三種方式中,第二種方式比較靈活。

第一、三種方式只能校驗不含負號「-」的數字,即輸入一個負數-199,輸出結果將是false;

而第二方式則可以透過修改正規表示式實現校驗負數,將正規表示式修改為「^-?[0-9]+」即可,修改為「-?[0-9]+.? [0-9]+”即可符合所有數字。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!