Một số hàm kiểm tra string là number trong java bằng pattern. (How to check if a String is a numeric type in Java?)






Bài viết này sẽ cung cấp một số hàm kiểm tra string là number với các định dạng số khác nhau (ex: 10, -10, +10) bằng pattern.







1. Chỉ có chữ số.

    public static boolean isNumericOnlyNumber(String str)
    {
        return str.matches("\\d+");
    }  

2. Số nguyên dương

      
    public static boolean isPositiveNumber(String str) {
        return str.matches("\\+\\d+");
    }

3. Số nguyên âm

  
    public static boolean isNegativeNumber(String str) {
        return str.matches("-\\d+");
    }  

4. Số, số nguyên dương, số nguyên âm

      
    public static boolean isNumberic(String str) {
        return str.matches("[+-]?\\d+");
    }   

Dưới đây là toàn bộ của source code demo.

/**
 * @(#)CheckStringIsNumber.java
 *
 * CheckStringIsNumber application
 *
 * @author BUI NGOC SON
 * @version 1.00 2014/2/2
 */

public class CheckStringIsNumber {
   
    public static void main(String[] args) {
       
        // TODO, add your application code
        System.out.println("Only number: " + isNumericOnlyNumber("10000"));
        System.out.println("Only positive number: " + isPositiveNumber("+10000"));
        System.out.println("Only negative number: " + isNegativeNumber("-10000"));
        //----------------------
        System.out.println("String is numberic: " + isNumberic("10000"));
        System.out.println("String is numberic: " + isNumberic("+10000"));
        System.out.println("String is numberic: " + isNumberic("-10000"));
    }
   
    public static boolean isNumericOnlyNumber(String str)
    {
        return str.matches("\\d+");
    }   
       
    public static boolean isPositiveNumber(String str) {
        return str.matches("\\+\\d+");
    }
   
    public static boolean isNegativeNumber(String str) {
        return str.matches("-\\d+");
    }   
       
    public static boolean isNumberic(String str) {
        return str.matches("[+-]?\\d+");
    }       

}

Sau khi chay ứng dụng bạn sẽ có kết quả như sau:

















No comments:

Post a Comment