正则表达式范围在 0 到 100 之间,包括两位小数 [英] Regex range between 0 and 100 including two decimal
问题描述
我正在尝试找出执行以下操作的正则表达式.以下两个条件都必须为真:1) 0 到 100 之间(含)2) 可以只包含一位或两位小数但不是必须的.
I'm trying to figure out a regex expression that does the following. Both conditions below must be true: 1) Between 0 and 100 inclusive 2) Can contain one or two decimals only but not obligatory.
它不应该允许 100.01 或 100.1100 是最大值,或 100.0 或 100.00
It should not allow 100.01 or 100.1 100 is the maximum value, or 100.0 or 100.00
我试过 ^(100(?:\.00)?|0(?:\.\d\d)?|\d?\d(?:\.\d\d)?)$
这帮助我解决了这个问题但这不接受 99.0
(一位小数).我可能非常接近.
I tried ^(100(?:\.00)?|0(?:\.\d\d)?|\d?\d(?:\.\d\d)?)$
which helped me in this question
but this does not accept 99.0
(one decimal).
I'm probably very close.
推荐答案
您只需要将每个第二个十进制数字设为可选:
You just need to make each second decimal digit optional:
^(?:100(?:\.00?)?|\d?\d(?:\.\d\d?)?)$
^ ^
查看更新的正则表达式演示.0(?:\.\d\d)?
替代方案被 \d?\d(?:\.\d\d)?
一个(如根据 塞巴斯蒂安的评论),因此可以删除.
See the updated regex demo. The 0(?:\.\d\d)?
alternative is covered by \d?\d(?:\.\d\d)?
one (as per Sebastian's comment) and can thus be removed.
?
量词匹配它所量化的子模式的一次或零次出现.
The ?
quantifier matches one or zero occurrences of the subpattern it quantifies.
模式详情:
^
- 字符串的开始(?:
- 交替组的开始:100(?:\.00?)?
-100
、100.0
或100.00
(.00
是可选的,最后一个0
也是可选的)\d?\d(?:\.\d\d?)?
- 一个可选数字,后跟一个强制性数字,后跟一个可选的点、数字和 一个可选的数字.
^
- start of string(?:
- start of an alternation group:100(?:\.00?)?
-100
,100.0
or100.00
(the.00
is optional and the last0
is optional, too)\d?\d(?:\.\d\d?)?
- an optional digit followed by an obligatory digit followed with an optional sequence of a dot, a digit and an optional digit.
这篇关于正则表达式范围在 0 到 100 之间,包括两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!