Best implementation for an isNumber(string) method

前端 未结 19 2536
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

19条回答
  •  独厮守ぢ
    2020-12-15 20:29

    I think people here is missing a point. The use of the same pattern repeatedly has a very easy optimization. Just use a singleton of the pattern. Doing it, in all my tests the try-catch approach never have a better benchmark than the pattern approach. With a success test try-catch takes twice the time, with a fail test it's 6 times slower.

    public static final Pattern INT_PATTERN= Pattern.compile("^-?[0-9]+(\\.[0-9]+)?$");
    
    public static boolean isInt(String s){
      return INT_PATTERN.matcher(s).matches();
    }
    

提交回复
热议问题