天天看點

Java判斷一個字元串是不是數字

    如果隻是判斷,可與用Integer.parseInt(String),或者Long.parseLong(String)...

    如果是數字,就沒有異常,如果有異常,就不是數字

    或者用正規表達式

    return string.matches("\\d+\\.?\\d*"));

    解釋:

    \\d+表示一個或者多個數字

    \\.?  表示一個或這沒有小數點  \\d * 表示0個或者多個數字

關于matches方法,找到:http://zhidao.baidu.com/link?url=SKz5DEgESY5hkG8y10rNEMTJZmrL7fkPJkpieAH5JXJj0Zgs6oi0W6c9cuP2w864zUf_BAY2I9LnnwUtCOSuaq

java.lang包中的String類,java.util.regex包中的Pattern,Matcher類中都有matches()方法。
都與正規表達式有關。下面我分别舉例:(字元串:"abc",正規表達式: "[a-z]{3}")

String類的方法:
boolean  b  = "abc".matches("[a-z]{3}"
System.out.println(b);              

Pattern類中的方法:
boolean  b  = Pattern.matches("[a-z]{3}","abc");
System.out.println(b);              

Matcher類中的方法:
Pattern p = Pattern.compile("[a-z]{3}");
Matcher m = p.matcher("acc");
boolean  b  =m.matches()
System.out.println(b);