正则表达式匹配2位数,可选小数,两位数 [英] Regex to match 2 digits, optional decimal, two digits

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

问题描述

我花了半个小时才弄明白,也许有人能很快想出.

I've spent half an hour trying to get this, maybe someone can come up with it quickly.

我需要一个正则表达式来匹配一位或两位数字,后跟一个可选的小数点,后跟一位或两位数字.

I need a regular expression that will match one or two digits, followed by an optional decmial point, followed by one or two digits.

例如,它应该完全匹配这些字符串:

For example, it should match these strings in their entirety:

3
33
.3
.33
33.3
33.33

3
33
.3
.33
33.3
33.33

并且不匹配小数点前后超过 2 位的任何内容.

and NOT match anything with more than 2 digits before or after the decmial point.

推荐答案

已更改以适应其他反馈.

我理解你的意思是,如果没有小数点,那么就不应该再有两位数了.所以应该是这样:

I understood you to mean that if there is no decimal point, then there shouldn't be two more digits. So this should be it:

\d{0,2}(\.\d{1,2})?

在大多数实现中,这应该可以解决问题.如果没有,您可以使用:

That should do the trick in most implementations. If not, you can use:

[0-9]?[0-9]?(\.[0-9][0-9]?)?

这应该适用于我见过的每个实现.

And that should work on every implementation I've seen.

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

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