【问题标题】:Regular Expression to validate empty fields正则表达式验证空字段
【发布时间】:2014-03-27 04:31:05
【问题描述】:

我有一个使用正则表达式验证小数和自然数的表单,但我有一个问题,这不能验证空字段。我的正则表达式是这样的:

"^([0-9])+\.[0-9]|[0-9]$"

我该怎么做才能让这个正则表达式验证空字段?谢谢。

【问题讨论】:

    标签: regex


    【解决方案1】:

    使用这个正则表达式来处理数字(只有正数)和空。

    ^(?:[0-9]+(?:\.[0-9]+)?)?$
    

    正则表达式的解释是:

    NODE                     EXPLANATION
    --------------------------------------------------------------------------------
      ^                        the beginning of the string
    --------------------------------------------------------------------------------
      (?:                      group, but do not capture (optional
                               (matching the most amount possible)):
    --------------------------------------------------------------------------------
        [0-9]+                   any character of: '0' to '9' (1 or more
                                 times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        (?:                      group, but do not capture (optional
                                 (matching the most amount possible)):
    --------------------------------------------------------------------------------
          \.                       '.'
    --------------------------------------------------------------------------------
          [0-9]+                   any character of: '0' to '9' (1 or
                                   more times (matching the most amount
                                   possible))
    --------------------------------------------------------------------------------
        )?                       end of grouping
    --------------------------------------------------------------------------------
      )?                       end of grouping
    --------------------------------------------------------------------------------
      $                        before an optional \n, and the end of the
                               string
    

    【讨论】:

    • 谢谢大家,我证明了你的所有建议,但它根本没有解决我的问题,仍然允许输入空字段,我可能解释得不好,我希望我的正则表达式不允许注册空字段。
    • @Jeason 你是对的,你没有解释清楚。我们让你的意思是允许空,这导致了问题。因此,解决方法是删除$ 之前的?。最后是^(?:[0-9]+(?:\.[0-9]+)?)$,不允许有空。
    【解决方案2】:

    你是这个意思吗?

    "^(?:([0-9])+\.[0-9]*|[0-9]|)$"
    

    这个正则表达式包含一个额外的没有字符的可能性。

    【讨论】:

      【解决方案3】:

      试试:

      ^([0-9]+\.[0-9]*|[0-9]*)$
      

      这个:

      • 修复了小数点后只接受1位数字的问题,
      • 解决了您只接受单个数字的自然数的问题,
      • 修复了两种情况下字段首尾不匹配的问题,
      • 允许 0 位数字,这是一个空字段。

      【讨论】:

        【解决方案4】:

        谢谢大家,

        我证明了你所有的建议,但它根本没有解决我的问题, 仍然允许输入空白字段,我可能解释得不好, 我希望我的正则表达式不允许注册空字段。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-06
          • 1970-01-01
          • 2012-07-12
          • 2021-11-28
          • 1970-01-01
          • 2021-08-15
          • 1970-01-01
          相关资源
          最近更新 更多