자바 문자열 이 숫자 인지 아 닌 지 판단 합 니 다.

2110 단어
org. apache. comons. lang 사용 하기
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

정규 표현 식
   
 /**
     *         
     * @param str      ,    -19162431.1254,   BigDecimal  ,  -1.91624311254E7
     * @return
     * @author yutao
     * @date 2016 11 14   7:41:22
     */
    public static boolean isNumeric(String str) {
        //                     
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//          。
        }
 
        Matcher isNum = pattern.matcher(bigStr); // matcher    
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

인터넷 에 이런 자료 가 많 습 니 다. 제 가 또 한 편 을 쓴 이 유 는 오늘 인터넷 에서 준 방법 을 실천 할 때 많은 bug 를 발 견 했 습 니 다.  그래서 내 가 알 아서 정리 할 게.다른 사람 에 게 붙 여 넣 은 것 을 복사 할 때 도 실천 하 는 것 이 좋다.  실천 하지 않 으 면 자신 이 얻 은 것 은 잘못된 방법 일 수도 있 고 다른 사람 을 오도 할 수도 있다!
JAVA 자체 함수 로.
public static boolean isNumericZidai(String str) {
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

그 중에서 Character. isDigit 방법: 지정 한 문자 가 숫자 인지 확인 하거나 판단 합 니 다.이런 방법 은 분명히 음 수 를 판단 할 수 없다.

좋은 웹페이지 즐겨찾기