Regex greater than zero with 2 decimal places

倖福魔咒の 提交于 2019-12-17 10:35:05

问题


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

回答1:


How about this:

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

Explanation:

^            # 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

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



回答2:


The code below allows both , and ..

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



回答3:


[0-9]+\.[0-9]{1,2}

That will find:

  • At least one number
  • A decimal point
  • One or two digits after the decimal point.



回答4:


/^[0-9]*(\.{1})?([0-91-9][1-9])?$/

try this it passes all your cases




回答5:


This expression will not allow any white spaces in beginning and last

/^\d*(?:\.\d{1,2})*$/


来源:https://stackoverflow.com/questions/8609714/regex-greater-than-zero-with-2-decimal-places

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!