Validate if a given string is numeric.
Some examples:
"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
public class Solution {
public boolean isNumber(String s) {
String sTrim = s.trim();
if(sTrim.length()==0) return false;
if(sTrim.contains(" ")) return false;
String pattern1 = "", pattern2 = "";
if(sTrim.contains("e")){
int indexE = sTrim.indexOf('e');
String beforeE="", afterE="";
if(indexE!=-1){
beforeE = sTrim.substring(0,indexE);
afterE = sTrim.substring(indexE+1, sTrim.length());
indexE = sTrim.indexOf('e', indexE+1);
if(indexE!=-1) return false;
}
pattern1 = "^[+,-]?[0-9]+$";
if(!afterE.matches(pattern1))
return false;
if(beforeE.contains(".")){
pattern1 = "^[+,-]?[0-9]*[.]{1}[0-9]+$";
pattern2 = "^[+,-]?[0-9]+[.]{1}[0-9]*$";
if(beforeE.matches(pattern1)||beforeE.matches(pattern2)) return true;
else return false;
}else{
pattern1 = "^[+,-]?[0-9]+$";
if(beforeE.matches(pattern1)) return true;
else return false;
}
}
else{
if(sTrim.contains(".")){
pattern1 = "^[+,-]?[0-9]+[.]{1}[0-9]*$";
pattern2 = "^[+,-]?[0-9]*[.]{1}[0-9]+$";
if(sTrim.matches(pattern1)||sTrim.matches(pattern2)) return true;
else return false;
}
else{
pattern1 = "^[+,-]?[0-9]+$";
if(sTrim.matches(pattern1)) return true;
else return false;
}
}
}
Note:
“.3”也算valid number!"3."也算valid number!但"."前后不可同时为空字符,所以要用或判断。
"7e69e"在java中用split分割,长度为2,最后不算第二个e后的空字符,所以不能检查如“e123e”格式的字符串。所以用indexOf函数查找字符"e",然后用substring获取"e"前后字符。string.indexOf('e',index)查找从string的index位置开始有无字符'e'。
科学计数法e后可以加+或-号,后面跟数字。