2012-04-26 34 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