十进制数的正则表达式

时间:2017-12-27 04:01:09

标签: javascript regex

我需要使用javascript对数字字符串进行验证,以确保该数字在小数点后最多为3位,在小数点前最多为3位。

有效

111

111.11

11.1

1.1

11.111

无效

1111

11.4444

1111.11

1111.1111

1 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式

^(?=\d)(?!0(?![.]))(?:\d{0,3})(?:[.]\d{1,3})?$

Regex Demo

正则表达式细分

^ #Start of string
 (?=\d) #Lookahead to ensure there is a dot or number
 (?!0(?![.])) #Negative lookahead to ensure there is no 0 in starting followed by .
 (?:\d{0,3}) #Match at most three digits before decimal
 (?:[.]\d{1,3})? #Match at most three digits after decimal. If there is a dot there should be at least one digit after dot
$ #End of string