《Java知识应用》Java 判断字符串是否为数字
正则表达式:(-|\\+)?([1-9]\\d*\\.?\\d*)|(0\\.\\d*[0-9])
案例:
public class NumberUtil { /** * 判断是否为数字 * @param str * @return */ public static boolean isDecimal(String str) { if (str == null || Objects.equals(str,"")) { return false; } else { String REGEX = "(-|\\+)?([1-9]\\d*\\.?\\d*)|(0\\.\\d*[0-9])"; Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(str); return m.matches(); } } public static void main(String[] args) { System.out.println(isDecimal("0.0")); System.out.println(isDecimal("1.0")); System.out.println(isDecimal("-1.0")); System.out.println(isDecimal("+1000000.0")); System.out.println(isDecimal("+1000000")); System.out.println(isDecimal("-1000000")); System.out.println(isDecimal("")); System.out.println(isDecimal("127.0.0.1")); System.out.println(isDecimal(".127")); System.out.println(isDecimal("s.127")); } }
运行结果:
This moment will nap, you will have a dream; But this moment study,you will interpret a dream.