簡體   English   中英

帶小數點的正則表達式

[英]Regular expression with decimal point

我正在嘗試使用正則表達式驗證文本框...

  regex expression=(\d{0,4})?([\.]{1})?(\d{0,2})

小數點有問題。 小數點是可選的。 正則表達式只能驗證小數點后一位。

    example 1.00 ,23.22 , .65 is valid
    1..  or  23.. is invalid.

有什么建議可以改善我的正則表達式嗎?

試試這個: ^\\d{1,4}(\\.\\d{1,2})?$

它應該匹配:

1
200
9999
12.35
522.4

但不是 :

1000000
65.
.65
10.326
65..12

編輯:

如果要匹配65.或9999。請改用此匹配項(請參閱注釋):

^\d{1,4}(\.(\d{1,2})?)?$

改用應用邏輯

雖然您當然可以為此構造一個正則表達式,但是檢查數據類型或類似乎更簡單,或者只需掃描輸入內容中的小數然后對它們進行計數即可。 例如,使用Ruby:

  • 檢查值是浮點數還是整數。

     # Literal value is a float, so it belongs to the Float class. value = 1.00 value.class == Fixnum or value.class == Float => true # Literal value is an integer, so it belongs to the Fixnum class. value = 23 value.class == Fixnum or value.class == Float => true 
  • 計算小數位數,並確保不超過一個。

     # Literal value is a float. When cast as a string and scanned, # only one decimal should be found. value = 23.22 value.to_s.scan(/\\./).count <= 1 => true # The only way this could be an invalid integer or float is if it's a string. # If you're accepting strings in the first place, just cast all input as a # string and count the decimals it contains. value = '1.2.3' value.to_s.scan(/\\./).count <= 1 => false 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM