java正則表達式驗證整數、浮點數和日期


/** 

     * 檢查日期格式 
     * @param date 
     * @return 
     */ 
    public static boolean checkDate(String date) {  
        String eL = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|

(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?

((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|

(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1][0-9])|([2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";  
        Pattern p = Pattern.compile(eL);  
        Matcher m = p.matcher(date);  
        boolean b = m.matches();  
        return b;  
    }  
    /** 
     * 檢查整數 
     * @param num 
     * @param type "0+":非負整數 "+":正整數 "-0":非正整數 "-":負整數 "":整數 
     * @return 
     */ 
    public static boolean checkNumber(String num,String type){  
        String eL = "";  
        if(type.equals("0+"))eL = "^\\d+$";//非負整數  
        else if(type.equals("+"))eL = "^\\d*[1-9]\\d*$";//正整數  
        else if(type.equals("-0"))eL = "^((-\\d+)|(0+))$";//非正整數  
        else if(type.equals("-"))eL = "^-\\d*[1-9]\\d*$";//負整數  
        else eL = "^-?\\d+$";//整數  
        Pattern p = Pattern.compile(eL);  
        Matcher m = p.matcher(num);  
        boolean b = m.matches();  
        return b;  
    }  
    /** 
     * 檢查浮點數 
     * @param num 
     * @param type "0+":非負浮點數 "+":正浮點數 "-0":非正浮點數 "-":負浮點數 "":浮點數 
     * @return 
     */ 
    public static boolean checkFloat(String num,String type){  
        String eL = "";  
        if(type.equals("0+"))eL = "^\\d+(\\.\\d+)?$";//非負浮點數  
        else if(type.equals("+"))eL = "^((\\d+\\.\\d*[1-9]\\d*)|(\\d*[1-9]\\d*\\.\\d+)|(\\d*[1-9]\\d*))$";//正浮點數  
        else if(type.equals("-0"))eL = "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";//非正浮點數  
        else if(type.equals("-"))eL = "^(-((\\d+\\.\\d*[1-9]\\d*)|(\\d*[1-9]\\d*\\.\\d+)|(\\d*[1-9]\\d*)))$";//負浮點數  
        else eL = "^(-?\\d+)(\\.\\d+)?$";//浮點數  
        Pattern p = Pattern.compile(eL);  
        Matcher m = p.matcher(num);  
        boolean b = m.matches();  
        return b;  
    } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM