正则表达式将百分比与十进制相匹配? [英] Regular expression to match a percentage with decimal?
问题描述
我正在尝试构建一个正则表达式(.NET)以匹配一个百分比,该百分比具有4个小数位。小数点后4位是必需的。范围如下:
I'm attempting to build a regular expression (.NET) to match a percentage with 4 decimal places. The 4 decimal places are required. The range looks like:
0.0001 to 100.0000
到目前为止,我想出了:
So far, I've come up with:
(?:[^0]+[1-100]{1,3})\.(?:\d{4})
但是,我不确定如何向此表达式添加其他一些要求。我需要:
However, I'm a bit unsure on how to add a few other requirements to this expression. I need:
- 小数点前没有前导零。允许42.4214,不允许042.4214。允许1.0000,但不允许001.0000。等等。
- 在小数点前最多允许3个字符,且不带前导零。
- 如果小数点后的数字为100,则不允许小数点后的数字为0000以外的任何数字,因此允许100.0000,但不允许100.0135。 (使用正则表达式是否有可能?)
我们非常感谢您的帮助!
Help is appreciated!
推荐答案
只需将 100.0000
的可能性作为单独的案例处理。容易匹配( 100\.0000
),很容易匹配其余部分( [1-9]?\d\ \.\d {4}
),因此将两者交替显示:
Just treat the 100.0000
possibility as a separate case. It's easy to match that (100\.0000
), and it's easy to match the rest ([1-9]?\d\.\d{4}
), so with the two as alternates you get:
^(100\.0000|[1-9]?\d\.\d{4})$
(假设您希望将其作为全文,否则忽略 ^
和 $
。
(Assuming you want it to be the whole text, otherwise leave out the ^
and the $
.
这篇关于正则表达式将百分比与十进制相匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!