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.
原題鏈接:https://oj.leetcode.com/problems/valid-number/
判斷字符串是否是數字。
規則:出現+, - 則必須是第一個,或前一個是e;有. 則是小數,之前不可有.和e;有e,則前面要有.,不能有e,並且後面要有.。
可用正則表達式來解答。
public static boolean isNumber(String s) { String reg = "[+-]?(\\d+\\.?|\\.\\d+)\\d*(e[+-]?\\d+)?"; return s.trim().matches(reg); }