简体   繁体   English

正则表达式验证三位数和一位小数

[英]regex to validate three digit with one decimal

I have written a regex to validate a number containing three digits and one decimal but it always return false in all cases. 我编写了一个正则表达式来验证包含三位数字和一个小数的数字,但是在所有情况下它总是返回false。

re = new RegExp("^\d{1,3}\.*\d{0,1}$");
re.test(33.0);

I tried many combinations but its not working. 我尝试了多种组合,但无法正常工作。 Aim is to validate a number at max 3 digit with one decimal and less than 100. I can handle the less than 100 part. 目的是验证最大3位数字(含小数点后小于100)。我可以处理小于100的部分。

You can use below code:: 您可以使用以下代码::

re = new RegExp("^[0-9]\d{0,2}(?:\.\d{0,1})?$");
re.test(33.0);

REGEX DEMO 正则演示

This one does what you want: 这是您想要的:

 var test = [ 123, 12.34, 100.1, 100, 12, 1.2, 1 ]; console.log(test.map(function (a) { return a+' :'+/^(?:100(?:\\.0)?|\\d{1,2}(?:\\.\\d)?)$/.test(a); })); 

Better use regex literal: 最好使用正则表达式文字:

var re = /^\d{1,2}(\.\d)?$/;
re.test(33.0);

When passing in numbers beware of floating point precision problems: 传递数字时,请注意浮点精度问题:

re.test(0.1 * 302); // false, because 0.1 * 302 results in 30.200000000000003 :-(

Remember to escape the \\ you regex sequence : 请记住要转义\\ you regex序列:

re = new RegExp("^\\\\d{1,3}\\.*\\\\d{0,1}$"); re = new RegExp(“ ^ \\\\ d {1,3} \\。* \\\\ d {0,1} $”);

re.test(33.0); 重新测试(33.0);

Instead of using Regex Expression Object try using direct javascript 代替使用正则表达式对象,请尝试使用直接javascript

/\d{1,3}\.*\d{0,1}$/.test(33.0)

 console.log(/\\d{1,3}\\.*\\d{0,1}$/.test(33.0)) 

If you want to use RegExp 如果您想使用RegExp

then try 然后尝试

new RegExp(/\d{1,3}\.*\d{0,1}$/,'i');
re.test(33.0);

 let re = new RegExp(/\\d{1,3}\\.*\\d{0,1}$/,'i'); console.log(re.test(33.0)); 

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

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