3 回答

TA貢獻1946條經驗 獲得超4個贊
使用以下內容:
/^\d*\.?\d*$/
^ -生產線的起點;
\d* -0或更多數字;
\.?-一個可選的點(由于在正則表達式中轉義,.是一個特殊字符);
\d* -0或更多數字(小數部分);
$ - 隊伍的盡頭。
這允許0.5小數而不是要求前導零,例如0.5

TA貢獻1812條經驗 獲得超5個贊
/\d+\.?\d*/
一個或多個數字(\d+),可選的句點(\.?),零個或多個數字(\d*)。
根據您的用法或正則表達式引擎,您可能需要添加開始/結束行錨點:
/^\d+\.?\d*$/

TA貢獻1788條經驗 獲得超4個贊
您需要如下所示的正則表達式才能正確執行此操作:
/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/
使用擴展修飾符(Perl支持)的帶空格的相同表達式:
/^ [+-]? ( (\d+ (\.\d*)?) | (\.\d+) ) $/x
或帶有注釋:
/^ # Beginning of string
[+-]? # Optional plus or minus character
( # Followed by either:
( # Start of first option
\d+ # One or more digits
(\.\d*)? # Optionally followed by: one decimal point and zero or more digits
) # End of first option
| # or
(\.\d+) # One decimal point followed by one or more digits
) # End of grouping of the OR options
$ # End of string (i.e. no extra characters remaining)
/x # Extended modifier (allows whitespace & comments in regular expression)
例如,它將匹配:
123
23.45
34。
.45
-123
-273.15
-42。
-.45
+516
+9.8
+2。
+.5
并將拒絕這些非數字:
。(單小數點)
- (負小數點)
+。(加上小數點)
(空字符串)
比較簡單的解決方案可能會錯誤地拒絕有效數字或匹配這些非數字。
- 3 回答
- 0 關注
- 936 瀏覽
添加回答
舉報