十进制或空白的正则表达式

时间:2010-03-24 14:55:17

标签: regex

对于这个可能很愚蠢的问题感到抱歉,但我试图将一个允许的正则表达式组合在一起:

小数点前有1或2个数字,小数点后有0-6个数字的数字。但是,如果需要,我还需要允许该字段为空白。

有效示例

0.952321
1.20394
12.12
25
Blank

无效的例子

123.45678
1.1234567

请有人帮忙吗?

7 个答案:

答案 0 :(得分:12)

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

应该做的伎俩。

\d     matches any digit
{n,m} specifies the number of occurrences
(?: ) creates an anonymous group
^     specifies the start of the string
$               the end of the string
?     means the group is optional

答案 1 :(得分:2)

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

管道前面的部分为空白。匹配一个或两个数字之后的部分,可选地后跟一个句点和最多六个数字。 ?:因此我们不会使用捕获组,除非需要。

希望这有帮助!

答案 2 :(得分:2)

您应该提供使用正则表达式的语言,其中许多功能允许您创建更易读的表达式。这是一个故障安全POSIX regex

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

如果小数部分是可选的,您可以使用

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

在行间读取,我扩展了可接受输入的定义而不是假设您只想捕获所描述格式的数字。

例如,这些数字将作为右边的数字捕获并且都是可接受的输入:

"0.952321    "  0.952321             (trailing spaces stripped)       
"   1.20394 "   1.20394              (leading and trailing spaces stripped)
"12.12"            12.12             (no leading or trailing spaces)
"12.123   "      12.123
" .1234 "         .1234              (no leading digit -- start with decimal)
"25"                 25              (no decimal) 
" "                " " ?             (space. space captured or not)
"12."               12.              (1 or 2 digits, decimal, no numbers after decimal)

不正常输入:

"."                                   just a decimal
"123456789"                           more than 2 digits lefthand
123                                       ""      "" 
123.45678 
1.1234567                             more than 6 digits right hand
[a-zA_Z]                              not a digit...

所以,鉴于此,这个正则表达式将会这样做:

/^\s*(                  # beginning of string and strip leading space                                
 | \d{1,2}\.?           # 1 or 2 digits with optional decimal
 | \d{0,2}\.\d{1,6}     # 0,1, 2 digits with a decimal with digits 
 | \s+                  # remove if you do not want to capture space
  )\s*$                 # trailing blanks to the end
/x

答案 5 :(得分:0)

一般情况下,即无限小数位:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$

答案 6 :(得分:0)

我会使用以下其中一种:

匹配所有小数:

(\d+\.\d+){0,1}

要在点之前/之后更具体,请尝试使用以下任何一项进行/变换:

(\d+\.\d{2}){0,1}
(\d{4}\.\d{2}){0,1}
相关问题