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

后端 未结 30 1487
野趣味
野趣味 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:32

    You can use the matches method of the string class. The [0-9] represents all the values it can be, the + means it must be at least one character long, and the * means it can be zero or more characters long.

    boolean isNumeric = yourString.matches("[0-9]+"); // 1 or more characters long, numbers only
    boolean isNumeric = yourString.matches("[0-9]*"); // 0 or more characters long, numbers only
    

提交回复
热议问题