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

时间:2016-02-01 11:27:50

标签: javascript angularjs regex

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

问题是它接受0.

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:2)

试试这个:

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

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

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