如何使用Regex和DocumentFilter限制点后两位数?

时间:2016-02-12 19:02:53

标签: java regex swing documentfilter

我试图让一些JTextFields只验证货币($ xxx.xx)这样的双数,我用DocumentFilter写了一个类来验证模式和字符的大小,但是我无法实现是用户可以键入多个点。

以下是我的代码示例:

private class LimitCharactersFilter extends DocumentFilter {

    private int limit;
    private Pattern regex = Pattern.compile( "\\d*(\\.\\d{0,2})?");
    private Matcher matcher;

    public LimitCharactersFilter(int limit) {           
        this.limit = limit;
    }

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        String fullText = fb.getDocument().getText(0, fb.getDocument().getLength()) + string;
        matcher = regex.matcher(fullText);
        if((fullText.length()) <= limit && matcher.matches()){
            fb.insertString(offset, string, attr);
        }else{
            Toolkit.getDefaultToolkit().beep();
        }
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        String fullText = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;
        matcher = regex.matcher(fullText);
        matcher = regex.matcher(text);
        if((fullText.length()) <= limit && matcher.matches()){
            fb.replace(offset,length, text, attrs);
        }else{
            Toolkit.getDefaultToolkit().beep();
        }
    }
}

以下是界面外观的图片: Interface Screenshot

验证字符的限制效果很好,但我想限制用户输入两位以上的数字(如果已有点)。

希望有人能帮助我。

1 个答案:

答案 0 :(得分:2)

To allow the dot to be entered when typing a float number, you can use

\\d*\\.?\\d{0,2}

Note that here,

  • \\d* - zero or more digits
  • \\.? - one or zero dots
  • \\d+ - one or more digits

Please also consider using VGR's suggestion:

new JFormattedTextField(NumberFormat.getCurrencyInstance());

This will create a text field that allows currency as input.