https://leetcode.com/problems/valid-number/
Valid Number
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.
正则技术哪家强
1 /** 2 * @param {string} s 3 * @return {boolean} 4 */ 5 var isNumber = function(s) { 6 s = s.trim(); 7 if(s !== "" && /^[-+]?(\d+\.?|\.\d+)\d*([e|E][-+]?\d+)?$/.test(s)){ 8 return true; 9 } 10 return false; 11 };
一开始没想清楚,每多一种情况就加一个else,写的乱七八糟,后来发现都可以合并。
1 /* 2 s = s.trim(); 3 if(s === ""){ 4 return false; 5 }else if(/^[-+]?[e|E]/.test(s)){ 6 return false; 7 }else if(/^[-+]?0$/.test(s)){ 8 return true; 9 }else if(/^[-+]?[0-9]*$/.test(s)){ 10 return true; 11 }else if(/^[-+]?[0-9]+\.[0-9]*$/.test(s)){ 12 return true; 13 }else if(/^[-+]?[0-9]*\.[0-9]+$/.test(s)){ 14 return true; 15 }else if(/^[-+]?[0-9]*[e|E][-+]?[0-9]+$/.test(s)){ 16 return true; 17 }else if(/^[-+]?([0-9]+\.[0-9]*)[e|E][-+]?[0-9]+$/.test(s)){ 18 return true; 19 }else if(/^[-+]?([0-9]*\.[0-9]+)[e|E][-+]?[0-9]+$/.test(s)){ 20 return true; 21 } 22 return false; 23 */
时间: 2024-10-09 22:38:31