简体   繁体   English

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

[英]Regex for float(x,y) possible?

In the following, float(x,y) means a number with x total digits and y of them can be decimals.下面的 float(x,y) 表示一个总位数为 x 的数字,其中 y 可以是小数。

I am trying to do client side validation for an html input field.我正在尝试对 html 输入字段进行客户端验证。 The field corresponds to a MySQL column with data type float(x,y).该字段对应于数据类型为 float(x,y) 的 MySQL 列。 I know I can define a pattern for float(5,2) with lots of 'ors'.我知道我可以为带有很多“或”的 float(5,2) 定义一个模式。 Is there an efficient way of generating a regex for this such that I can encode it in my web document?有没有一种有效的方法可以为此生成正则表达式,以便我可以在我的网络文档中对其进行编码?

Something of a workaround is to specify "\\d+(.\\d{1,y})?"一种解决方法是指定“\\d+(.\\d{1,y})?” and then set 'maxlength=x+1'.然后设置'maxlength=x+1'。 It is 'x+1' because the decimal place is counted.它是'x+1',因为计算小数位。 This then will allow the submission of an integer of length 'x+1' contrary to specification.这将允许提交与规范相反的长度为“x+1”的整数。 I realize I can do Javascript validation but I want to do it with HTML validation.我意识到我可以做 Javascript 验证,但我想用 HTML 验证来做。

You can first check the total length with a lookahead and then check for the length of numbers after the decimal point.您可以先检查总长与前瞻,然后检查数字的小数点后的长度。

If you want X total number of digits and at most Y decimal points, you can use:如果您想要X 个总位数和最多Y 个小数点,您可以使用:

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

Explanation:解释:

^         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

Note that you do not need to check the length of the whole part since you are already checking for the total length and the length of digits after the decimal so the part before the decimal point is automatically correct.请注意,您不需要检查整个部分的长度,因为您已经在检查总长度和小数点后的数字长度,因此小数点前的部分自动正确。

Example:例子:

For X = 5 and Y = 2 , you will have:对于X = 5Y = 2 ,您将拥有:

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

Regex101 demo Regex101 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM