[英]Regex for float(x,y) possible?
下面的 float(x,y) 表示一個總位數為 x 的數字,其中 y 可以是小數。
我正在嘗試對 html 輸入字段進行客戶端驗證。 該字段對應於數據類型為 float(x,y) 的 MySQL 列。 我知道我可以為帶有很多“或”的 float(5,2) 定義一個模式。 有沒有一種有效的方法可以為此生成正則表達式,以便我可以在我的網絡文檔中對其進行編碼?
一種解決方法是指定“\\d+(.\\d{1,y})?” 然后設置'maxlength=x+1'。 它是'x+1',因為計算小數位。 這將允許提交與規范相反的長度為“x+1”的整數。 我意識到我可以做 Javascript 驗證,但我想用 HTML 驗證來做。
您可以先檢查總長與前瞻,然后檢查數字的小數點后的長度。
如果您想要X 個總位數和最多Y 個小數點,您可以使用:
^(?=.{X+1}$)([1-9]\d*|0)\.\d{1,Y}$
解釋:
^ asserts you are in the start position of the line
(?= lookahead (zero length) match for:
.{X + 1} X+1 characters
$ end of line //now you have asserted the total length
the whole part either
0 is a single zero
[1-9]\d* more than a single digit and does not start with zero
\. a dot for the decimal point
\d{1,Y} at least 1 and at most Y digits
$ asserts end of line
請注意,您不需要檢查整個部分的長度,因為您已經在檢查總長度和小數點后的數字長度,因此小數點前的部分自動正確。
例子:
對於X = 5
和Y = 2
,您將擁有:
^(?=.{8}$)([1-9]\d*|0)\.\d{1,2}$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.