public void StringIsNumber(){ String str = "2.1"; Pattern pattern = Pattern.compile("-?[0-9]*.?[0-9]*"); Matcher matcher = pattern.matcher((CharSequence) str); boolean result = matcher.matches(); if(result == true){ System.out.print("数字"); }else { System.out.print("不是数字"); } }
解释下正则表达式的内容:
X? | X,一次或一次也没有 |
X* | X,零次或多次 |
关于正则表达式的相关内容:
https://www.cnblogs.com/Lowp/archive/2012/09/22/2698574.html