正则表达式大于零,小数点后两位 [英] Regex greater than zero with 2 decimal places

查看:570
本文介绍了正则表达式大于零,小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个RegEx用于一个数字值,该数字值最多可以有两个小数点,它们大于零,并且在one列中可能有零,也可能没有零。我还应该添加....全部数字都可以。见下面的记忆,但是可能会有前导空格或尾随空格

I need a RegEx for a numeric value with up to two decimal places greater than zero and may or may not have a zero in the ones column. I should also add....whole numbers are fine. See somments below but there could be leading or trailing white spaces

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测试:

Test in 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

这篇关于正则表达式大于零,小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆