What's the best way to check if a String represents an integer in Java?

后端 未结 30 1934
野趣味
野趣味 2020-11-22 05:45

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.         


        
30条回答
  •  耶瑟儿~
    2020-11-22 06:26

    Just one comment about regexp. Every example provided here is wrong!. If you want to use regexp don't forget that compiling the pattern take a lot of time. This:

    str.matches("^-?\\d+$")
    

    and also this:

    Pattern.matches("-?\\d+", input);
    

    causes compile of pattern in every method call. To used it correctly follow:

    import java.util.regex.Pattern;
    
    /**
     * @author Rastislav Komara
     */
    public class NaturalNumberChecker {
        public static final Pattern PATTERN = Pattern.compile("^\\d+$");
    
        boolean isNaturalNumber(CharSequence input) {
            return input != null && PATTERN.matcher(input).matches();
        }
    }
    

提交回复
热议问题