Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

 

不得不说,这题做的让我感受到了这个世界满满的恶意。。。吐槽归吐槽,题还是要做,经过一大番的if-else的修改无果后,不得不重新考虑这题的解法。

参考一下http://www.2cto.com/kf/201310/251338.html 的解法,感谢原作者

思路就是利用正则表达式,所以重点在如何找出匹配的模式串,话不多说,直接贴代码

 1 public boolean isNumber(String s) {
 2         if(s.trim().isEmpty()){  
 3             return false;  
 4         }  
 5         String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";  
 6         if(s.trim().matches(regex)){  
 7             return true;  
 8         }else{  
 9             return false;  
10         } 
11     }

 

posted @ 2014-05-21 11:11  秋风一片叶  阅读(90)  评论(0编辑  收藏  举报