简体   繁体   English

正则表达式匹配最多 2 位数字和最多 2 位小数的数字

[英]Regular expression to match a number with 2 digits at most and optionally 2 decimals at most

I've been searching for the past few days but the only kinds of regex that I find are like this:过去几天我一直在寻找,但我发现的唯一正则表达式是这样的:

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

This works well with inputs like:这适用于以下输入:

9
99
9.9
9.99
99.9
99.99
.9
.99

Everything's OK with those, but it also happens to accept inputs like一切都很好,但它也恰好接受像

999
9999

I don't want this to happen.我不希望这种情况发生。 What can I do to solve this problem?我能做些什么来解决这个问题?

You can use this regex with alternation:您可以交替使用此正则表达式:

^(?:\d{1,2}|\d{0,2}\.\d{1,2})$

RegEx Demo正则表达式演示

RegEx Description:正则表达式说明:

^           # start
(?:         # start non-capturing group
   \d{1,2}  # match 1 or 2 digits
   |        # OR
   \d{0,2}  # match 0 to 2 digits
   \.       # followed by DOT
   \d{1,2}  # match 1 or 2 digits
)           # end non-capturing group
$           # end

使用以下正则表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM