精度为 2 的小数的简单正则表达式 [英] Simple regular expression for a decimal with a precision of 2

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

问题描述

精度为 2 的小数的正则表达式是什么?

What is the regular expression for a decimal with a precision of 2?

有效示例:

123.12
2
56754
92929292929292.12
0.21
3.1

无效示例:

12.1232
2.23332
e666.76

小数点可以是可选的,也可以包括整数.

The decimal point may be optional, and integers may also be included.

推荐答案

有效的正则表达式标记因实现而异.通用形式是:

Valid regex tokens vary by implementation. A generic form is:

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

更紧凑:

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

两者都假设小数点前至少有一位,小数点后至少有一位.

Both assume that both have at least one digit before and one after the decimal place.

要要求整个字符串是这种形式的数字,请将表达式包装在开始和结束标记中,例如(在 Perl 形式中):

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

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

匹配小数点前没有前导数字的数字 (.12) 和有尾随句点的整数 (12.),同时排除输入单个句点 (.),请尝试以下操作:

To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

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

<小时>

已添加

将小数部分包裹在 ()? 中以使其可选.请注意,这不包括 12 之类的形式. 包括它更像是 ^\d+\\.?\d{0,2}$.


Added

Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

使用 ^\d{1,6}(\.\d{1,2})?$ 停止重复并限制十进制值的整个部分.

Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

这篇关于精度为 2 的小数的简单正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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