How to check if a String is numeric in Java

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

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

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

    I modified CraigTP's solution to accept scientific notation and both dot and comma as decimal separators as well

    ^-?\d+([,\.]\d+)?([eE]-?\d+)?$
    

    example

    var re = new RegExp("^-?\d+([,\.]\d+)?([eE]-?\d+)?$");
    re.test("-6546"); // true
    re.test("-6546355e-4456"); // true
    re.test("-6546.355e-4456"); // true, though debatable
    re.test("-6546.35.5e-4456"); // false
    re.test("-6546.35.5e-4456.6"); // false
    

提交回复
热议问题