0

我正在尝试验证一个文本框,我希望用户只输入 0.1 和 4.0 之间,我正在使用以下正则表达式

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

事情是甚至接受 4.1 等等,直到 4.9

请对我如何解决此问题有任何想法

谢谢

4

1 回答 1

4

试试这个

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

编辑

我添加了非捕获组。

正如塞浦路斯所问,这里有一个解释:我将原始正则表达式限制为 3.9,并为 4(.0) 添加了另一个条件

NODE                     EXPLANATION
  ^                        //the beginning of the string
  (?:                      //group, but do not capture:
    [0-3]                  //any character of: '0' to '3'
    (?:                    //group, but do not capture (optional):
      \.                   //'.'
      [0-9]+               //any character of: '0' to '9' (1 or more times)
    )?                     //end of grouping
   |                       //OR
    4                      //'4'
    (?:                    //group, but do not capture (optional):
      \.                   //'.'
      0                    //'0'
    )?                     //end of grouping
  )                        //end of grouping
  $                        //before an optional \n, and the end of the string
于 2012-04-26T13:17:15.080 回答