百分比大于0且小于或等于100的正则表达式

时间:2022-09-18 13:04:40

I searched the web and came up with: /(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/

我在网上搜索并提出:/(^ 100(\。0 {1,2})?$)|(^([1-9]([0-9])?| 0)(\。[ 0-9] {1,2})?$)/

The problem is it accepts 0.

问题是它接受0。

2 个解决方案

#1


4  

Perhaps you are thinking about the problem wrongly. A better method if possible would be to convert the string to a double and perform the check using arithmetic operators.

也许你错误地思考这个问题。如果可能的话,更好的方法是将字符串转换为double并使用算术运算符执行检查。

const examplePercentage = '0.5%';
const percentageAsFloat = parseFloat(examplePercentage); // 0.5
const isValid = percentageAsFloat > 0 && percentageAsFloat <= 100; // true

#2


2  

Try this one:

试试这个:

^0*(100(\.0{1,2})?|[1-9][0-9]?(\.[0-9]{1,2})?|0\.(0[1-9]|[1-9][0-9]?))$

It handles >= 1 different from < 1.

它处理> = 1与<1不同。

But I would go with parsing the number and checking it's value.

但我会解析数字并检查它的值。

#1


4  

Perhaps you are thinking about the problem wrongly. A better method if possible would be to convert the string to a double and perform the check using arithmetic operators.

也许你错误地思考这个问题。如果可能的话,更好的方法是将字符串转换为double并使用算术运算符执行检查。

const examplePercentage = '0.5%';
const percentageAsFloat = parseFloat(examplePercentage); // 0.5
const isValid = percentageAsFloat > 0 && percentageAsFloat <= 100; // true

#2


2  

Try this one:

试试这个:

^0*(100(\.0{1,2})?|[1-9][0-9]?(\.[0-9]{1,2})?|0\.(0[1-9]|[1-9][0-9]?))$

It handles >= 1 different from < 1.

它处理> = 1与<1不同。

But I would go with parsing the number and checking it's value.

但我会解析数字并检查它的值。