How to check if a String is numeric in Java

前端 未结 30 2590
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 05:59

    A well-performing approach avoiding try-catch and handling negative numbers and scientific notation.

    Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );
    
    public static boolean isNumeric( String value ) 
    {
        return value != null && PATTERN.matcher( value ).matches();
    }
    

提交回复
热议问题