带有两位小数的整数或浮点数的正则表达式 [英] regex for integer or floating point number with two decimals
问题描述
我想用正则表达式验证我的货币字段.我想允许以下模式条目
I want to validate my currency field with regex. I want to allow the following pattern entries
1.23
1
.45
0.56
56.00
不允许有逗号.我试过 \d+(\.\d\d)
但它只允许第一个、第四个和第五个条目.\d+(?:\.\d\d+)?
允许除第三个以外的所有.
No comma should be allowed. I've tried \d+(\.\d\d)
but it allows only first, fourth and fifth entries. \d+(?:\.\d\d+)?
allows all but third one.
推荐答案
在小数点前使用 \d*
而不是 \d+
来匹配零个或多个数字.还要添加锚点(^
和 $
),否则只要有任何匹配项,它就会通过.这也将验证一个空字符串,因此如有必要,您可以使用前瞻来确保至少有一个数字:
Use \d*
instead of \d+
before the decimal to match zero or more digits. Also add anchors (^
and $
) or else it will pass as long as there is any match available. This would also validate an empty string, so if necessary you can use a lookahead to make sure there is at least one digit:
^(?=.*\d)\d*(?:\.\d\d)?$
这篇关于带有两位小数的整数或浮点数的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!