javaregexswingjtextfielddocumentfilter

Why the following regular expression is not allowing numbers?


Well, this might sound as if it is a duplicate question but it is not. I have asked this question in connection with this question here. I have rewritten my DocumentFilter to use regular expressions. In validating a person's name I want only the following characters [a-zA-Z],',\S and ..

I have written my regular expression with the hope that it will solve this. It is working the way I want it but the fact that it is not allowing numbers when I have not yet set it to do so is puzzling me.

Question: Why is regex not allowing numbers?

This is the regular expression [\\_\\(\\)@!\"#%&*+,-:;<>=?\\[\\]\\^\\~\\{\\}\\|] and what it should not allow to be entered is commented in the code below:

My DocumentFilter is as follows:

public class NameValidator extends DocumentFilter{
@Override
public void insertString(FilterBypass fb, int off
                    , String str, AttributeSet attr) 
                            throws BadLocationException 
{
    // remove 0-9 !"#$%&()*+,-/:;<=>?@[\]^_`{|}~
    fb.insertString(off, str.replaceAll("^[\\_\\(\\)@!\"#%&*+,-:;<>=?\\[\\]\\^\\~\\{\\}\\|]", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
        , int len, String str, AttributeSet attr) 
                        throws BadLocationException 
{
    // remove 0-9 !"#$%&()*+,-/:;<=>?@[\]^_`{|}~
    fb.replace(off, len, str.replaceAll("^[\\_\\(\\)@!\"#%&*+,-:;<>=?\\[\\]\\^\\~\\{\\}\\|]", ""), attr);
   }
}

Here is my test class:

public class NameTest {

private JFrame frame;

public NameTest() throws ParseException {
    frame = new JFrame();
    initGui();
}

private void initGui() throws ParseException {

    frame.setSize(100, 100);
    frame.setVisible(true);
    frame.setLayout(new GridLayout(2, 1, 5, 5));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField name = new JTextField(10);
    ((AbstractDocument)name.getDocument()).setDocumentFilter(new NameValidator());
    frame.add(name);

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                NameTest nt = new NameTest();
            } catch (ParseException e) {

                e.printStackTrace();
            }

        }
     });
    }
  }

Solution

  • The reason is this part of your regex:

    ,-:
    

    Which matches any character in the range of , (ASCII 44) to : (ASCII 58), which includes all the numbers (ASCII 48-57 inclusive).

    If you escape the - it should work fine and not match numbers:

    [\\_\\(\\)@!\"#%&*+,\\-:;<>=?\\[\\]\\^\\~\\{\\}\\|]