简体   繁体   English

RegExp在小数点后三位放置零(0)

[英]RegExp Place zero(0) after three decimals

Hi all i need all these possible cases to be valid

0.001
0.320
0.009
0.0
0.3
0.9

let reqDecimal=/^(0(.\\d+)?|1(.0+)?)$/; 让reqDecimal = / ^(0(。\\ d +)?| 1(.0 +)?)$ /; I tried above code need to expected 3 decimal values not more than. 我尝试上面的代码需要期望不超过3个十进制值。

Simply replace both of your plus signs with {1,3) : 只需将您的两个加号替换为{1,3)

/^(0(.\d{1,3})?|1(.0{1,3})?)$/

This ensures that there are between 1 and 3 digits between each decimal: 这样可以确保每个小数之间的数字介于1到3之间:

 const regex = /^(0(.\\d{1,3})?|1(.0{1,3})?)$/; const amounts = [ "0.001", "0.320", "0.009", "0.0", "0.3", "0.9", "0.", "0.0000", "1.", "1.000", "1.0000" ] amounts.forEach(function(amount) { console.log(amount, "=", regex.test(amount)); }); 

This can also be seen working on Regex101 here . 这也可以在这里在Regex101上看到

You could probably use: 您可能会使用:

^(?:1|0)\.\d{1,3}$

If you are wanting to stay at or under 1.000 : 如果您想保持在1.000

^0\.\d{1,3}\b|1\.0{1,3}\b$

Examples : 例子

https://regex101.com/r/wKZseY/1 https://regex101.com/r/wKZseY/1
https://regex101.com/r/wKZseY/2 https://regex101.com/r/wKZseY/2

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

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