float(x,y) 的正则表达式可能吗?

Regex for float(x,y) possible?

下面的float(x,y)表示一个数字的总位数是x,其中y可以是小数。

我正在尝试对 html 输入字段进行客户端验证。该字段对应于数据类型为 float(x,y) 的 MySQL 列。我知道我可以用很多 'ors' 为 float(5,2) 定义一个模式。有没有一种有效的方法可以为此生成正则表达式,以便我可以在我的网络文档中对其进行编码?

一种解决方法是指定“\d+(.\d{1,y})?”然后设置 'maxlength=x+1'。是'x+1',因为是计算小数位的。这将允许提交一个长度为 'x+1' 的整数,这与规范相反。我知道我可以做 Javascript 验证,但我想用 HTML 验证来做。

可以先用lookahead检查总长度,再检查小数点后的数字长度

如果你想要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 = 5Y = 2,您将拥有:

^(?=.{8}$)([1-9]\d*|0)\.\d{1,2}$

Regex101 demo