为什么下面的正则表达式不允许数字?

Why the following regular expression is not allowing numbers?

好吧,这听起来好像是一个重复的问题,但事实并非如此。我已经就 this question here 提出了这个问题。我重写了 DocumentFilter 以使用正则表达式。在验证一个人的名字时,我只需要以下字符 [a-zA-Z]'\S.

我写了我的正则表达式,希望它能解决这个问题。它按照我想要的方式工作但是当我还没有设置它时它不允许数字的事实让我感到困惑。

问题:为什么regex不允许数字?

这是正则表达式[\_\(\)@!\"#%&*+,-:;<>=?\[\]\^\~\{\}\|],不允许输入的内容在下面的代码中注释:

我的DocumentFilter如下:

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);
   }
}

这是我的测试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();
            }

        }
     });
    }
  }

原因是您的正则表达式的这一部分:

,-:

匹配 , (ASCII 44) 到 : (ASCII 58) 范围内的任何字符,包括所有数字(ASCII 48-57,包括在内)。

如果您转义 - 它应该可以正常工作并且不匹配数字:

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