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

标签 java regex swing jtextfield documentfilter

嗯,这听起来好像是一个重复的问题,但事实并非如此。我问过这个与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);
   }
}

这是我的测试类:

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)。

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

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

关于java - 为什么下面的正则表达式不允许数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29792594/

相关文章:

java - 使用外部存储进行 Vert.x session 管理

java - 将 Katalon Studio 更新至版本 5.9.1 - ClassNotFoundException

java - 返回一个迭代器是什么意思? java

c - 过滤器 c 注释的正则表达式

mysql - 正则表达式,将 "22,09"替换为 "22.09"

java - 如何持久化或保存 JavaFX UI 状态?

java - 在 Swing 面板之间传递信息?

java - 异步原子数组

javascript - 用于匹配包含 URL 的字符串中的字母数字的正则表达式

java - 小程序顶部的 Jpanel