正则表达式大于零,保留 2 位小数

2024-04-24

我需要一个正则表达式来表示最多两位小数大于零的数值,并且个数列中可能有也可能没有零。我还应该添加......整数就可以了。请参阅下面的一些内容,但可能存在前导或尾随空格

Good values:
.1
0.1
1.12
123.12
92
092
092.13

Error values:
0
0.0
0.00
00
1.234
-1
-1.2
Anything less than zero

这个怎么样:

^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$

解释:

^            # Start of string
\s*          # Optional whitespace
(?=.*[1-9])  # Assert that at least one digit > 0 is present in the string
\d*          # integer part (optional)
(?:          # decimal part:
 \.          # dot
 \d{1,2}     # plus one or two decimal digits
)?           # (optional)
\s*          # Optional whitespace
$            # End of string

用Python测试:

>>> import re
>>> test = [".1", "0.1", "1.12", "123.12", "92", "092", "092.13", "0", "0.0", "0.00", "00", "1.234", "-1", "-1.2"]
>>> r = re.compile(r"^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$")
>>> for item in test:
...     print(item, "matches" if r.match(item) else "doesn't match")
...
.1 matches
0.1 matches
1.12 matches
123.12 matches
92 matches
092 matches
092.13 matches
0 doesn't match
0.0 doesn't match
0.00 doesn't match
00 doesn't match
1.234 doesn't match
-1 doesn't match
-1.2 doesn't match
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式大于零,保留 2 位小数 的相关文章

随机推荐