如何将 jtextfield 验证为特定格式?

How to validate a jtextfield to specific format?

我需要通过允许用户根据此格式 12345-1234567-1 仅输入 cnic 号码来验证 JTextField,我正在使用此正则表达式,但它不起作用。这是我的功能

private void idSearchKeyPressed(java.awt.event.KeyEvent evt) {
    String cnicValidator = idSearch.getText();

    if (cnicValidator.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")) {
        idSearch.setEditable(true);
    }
    else {
        idSearch.setEditable(false);
    }        
}

使用 JFormattedTextField 结合 MaskFormatter 来限制输入的开头。

像这样:

final JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final MaskFormatter mask;
        try {
            mask = new MaskFormatter("#####-#######-#");
        } catch (ParseException e) {
            throw new RuntimeException("Invalid format mask specified", e);
        }

        // You can optionally set a placeholder character by doing the following:
        mask.setPlaceholderCharacter('_');
        final JFormattedTextField formattedField = new JFormattedTextField(mask);

        frame.setSize(100, 100);
        frame.add(formattedField);
        frame.setVisible(true);