简体   繁体   中英

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. Please help me to solve this problem. Thanks in advance.

Well, 12. is not covered. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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