javascript 小数点前 6 位和小数点后 2 位的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28612649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:16:19  来源:igfitidea点击:

regex for 6 digits before and 2 digits after decimal

javajavascriptregex

提问by Harish Gupta

I need a regex in which decimal is optional. If decimal is there then there can be max 6 digits before and max 2 digits after decimal. If decimal is not there then max of 6 digits is valid.

我需要一个正则表达式,其中十进制是可选的。如果有小数,那么小数点前最多可以有 6 位数字,小数点后最多可以有 2 位数字。如果十进制不存在,则最多 6 位有效。

Regex tested :^\d{0,6}\.?\d{1,2}$

正则表达式测试:^\d{0,6}\.?\d{1,2}$

The above regex allows max of 8 digits without decimal. How can I change according to my needs so that if there is no decimal then it would take max of 6 digits?

上面的正则表达式允许最多 8 位没有小数。如何根据我的需要进行更改,以便如果没有小数,则最多需要 6 位数字?

VALID CASES

有效案例

123456.12  
21231  
123456  
15465.43  
23.34  
6.45  
.12

INVALID CASES

无效案例

12345678  
123456.331  

回答by vks

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

Try this.See demo.

试试这个。看演示。

https://regex101.com/r/oL9kE8/4

https://regex101.com/r/oL9kE8/4

Just make the (\.\d{1,2})decimal part optional.?

只需将(\.\d{1,2})小数部分设为可选。?