带小数点的正则表达式

时间:2012-08-05 03:50:40

标签: regex

我正在尝试使用正则表达式验证文本框...

  regex expression=(\d{0,4})?([\.]{1})?(\d{0,2})

我的小数点有问题。小数点是可选的。正则表达式只应验证一个小数点。

    example 1.00 ,23.22 , .65 is valid
    1..  or  23.. is invalid.

有关改进我的正则表达式的任何建议吗?

2 个答案:

答案 0 :(得分:5)

试试这个:^\d{1,4}(\.\d{1,2})?$

它应匹配:

1
200
9999
12.35
522.4

但不是:

1000000
65.
.65
10.326
65..12

修改:

如果你想匹配65.或9999.请改用(见评论):

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

答案 1 :(得分:0)

使用应用程序逻辑

虽然你当然可以构造一个正则表达式,但检查数据类型或类似乎更简单,或者只是扫描输入的小数,然后计算它们。例如,使用Ruby:

  • 检查该值是浮点数还是整数。

    # Literal value is a float, so it belongs to the Float class.
    value = 1.00
    value.class == Fixnum or value.class == Float
    => true
    
    # Literal value is an integer, so it belongs to the Fixnum class.
    value = 23
    value.class == Fixnum or value.class == Float
    => true
    
  • 计算小数,并确保不超过一个。

    # Literal value is a float. When cast as a string and scanned,
    # only one decimal should be found.
    value = 23.22
    value.to_s.scan(/\./).count <= 1
    => true
    
    # The only way this could be an invalid integer or float is if it's a string.
    # If you're accepting strings in the first place, just cast all input as a
    # string and count the decimals it contains.
    value = '1.2.3'
    value.to_s.scan(/\./).count <= 1
    => false