2012-04-26 33 views
0

我想验证一个文本框,我希望用户只有0.1和4.0之间的输入和我使用下面的正则表达式限制文本框使用正则表达式

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

的事情是即使接受4.1依此类推,直到4.9

任何想法我如何能解决这个问题

谢谢请

+0

使用'JFormattedTextField'组件? – user1329572 2012-04-26 13:15:48

+1

如果您正在验证数字,您需要使用RegEx的所有原因?解析它到一个数字并验证范围应该是最直接的方法.. – Nivas 2012-04-26 13:15:50

+0

@Nivas:问为什么使用正则表达式是彻头彻尾的无益。正则表达式是验证的方式 – CyprUS 2012-04-26 13:21:59

回答

4

试试这个

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

EDIT

我添加的非捕获基团。

而且塞浦路斯问,这里的解释: 我有限的原正则表达式上升到3.9,如果你正在使用Swing组件,为什么不添加其他条件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 
+0

感谢M8工作得很好:) – 2012-04-26 13:20:26

+0

也发布了一些解释。它会有帮助。 – CyprUS 2012-04-26 13:28:06