简体   繁体   English

仅数字和单点的正则表达式

[英]Regular Expression For Only Digits & A Single Dot

i need regular expression for : 我需要以下正则表达式:

one or two digits then . 然后是一两位数。 and one or two digits. 和一位或两位数。

Valid Expressions : 有效表达式:

1
1.5
11.5

Invalid Expression : 无效的表达:

0..
0.
11.

I have tried using the following Regex. 我尝试使用以下正则表达式。

^[0-9]{1,2}([.][0-9]{1,2})?$

but it does not validate when i enter 12. or something like that. 但是当我输入12.或类似的东西时它不会验证。 Please help me to solve this problem. 请帮我解决这个问题。 Thanks in advance. 提前致谢。

Well, 12. is not covered. 好吧, 12.不包括在内。 Neither by your specification (dot, followed by one or two digits), nor your examples, nor your regex (in fact, it's one of your examples for an invalid expression). 既不是您的规范(点,后跟一位或两位数字),也没有您的示例,也不是您的正则表达式(实际上,这是您的无效表达式示例之一)。 If you enter a dot, then there have to follow digits because both the dot and the trailing digits are in the same group. 如果输入点,则必须跟随数字,因为点和尾数均在同一组中。

You could make the digits optional, too: 您也可以将数字设置为可选:

^[0-9]{1,2}(\.[0-9]{0,2})?$

That is, a dot may also be followed by zero digits instead of just one or two. 也就是说,一个点也可以跟着零个数字,而不只是一个或两个。

In JavaScript \\d and [0-9] are equivalent, by the way, so you can shorten it a bit: 顺便说一下,在JavaScript中, \\d[0-9]是等效的,因此您可以将其缩短一点:

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

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

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