正则表达式大于零,小数点后2位

时间:2011-12-22 21:05:49

标签: regex decimal

我需要一个RegEx来表示一个数值,最多两个小数位大于零,并且在一列中可能有也可能没有零。我还应该补充....整数都很好。请参阅下面的内容,但可能有前导或尾随空格

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

5 个答案:

答案 0 :(得分:49)

这个怎么样:

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

答案 1 :(得分:1)

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

那会找到:

  • 至少一个号码
  • 小数点
  • 小数点后的一位或两位数。

答案 2 :(得分:1)

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

试试这会传递你的所有案件

答案 3 :(得分:1)

以下代码同时允许,.

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

答案 4 :(得分:-3)

此表达式不允许在开头和最后一个空格

foreach (var handler in this.preRequestHandlers)
{
    await handler.Handle(request);
}