Nat*_*ara 0 java regex swing jtextfield documentfilter
好吧,这可能听起来好像是一个重复的问题,但事实并非如此.我在这里就这个问题提出了这个问题.我已经重写了我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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试类:
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();
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
原因是你的正则表达式的这一部分:
,-:
Run Code Online (Sandbox Code Playgroud)
它匹配,(ASCII 44)到:(ASCII 58)范围内的任何字符,其中包括所有数字(包括ASCII 48-57).
如果你逃避-它应该工作正常而不匹配数字:
[\\_\\(\\)@!\"#%&*+,\\-:;<>=?\\[\\]\\^\\~\\{\\}\\|]
Run Code Online (Sandbox Code Playgroud)