2015-04-22 58 views
0

好吧,這聽起來好像是一個重複的問題,但事實並非如此。我已經在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 !"#$%&()*+,-/:;<=>[email protected][\]^_`{|}~ 
    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 !"#$%&()*+,-/:;<=>[email protected][\]^_`{|}~ 
    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(); 
      } 

     } 
    }); 
    } 
    } 
+1

了'0-9'數字只是添加到正則表達式:'[0-9 \\ _ \\(\\ )@!\「#%&*+,-:; <> =?\\ [\\] \\^\\〜\\ {\\} \\ |]' –

+0

@stribizhev呃,我的意思是說正則表達式不允許數字** BEROFE我已經把它設置成這樣做了,就像你以前所做的那樣,我正要按照你所做的那樣做,但在此之前它已經不允許使用數字了!我希望我已經解釋得更好了 – JWizard

+0

@Giovanrich :我忽略了', - :',它確實已經捕獲了您刪除的數字。 –

回答

6

的原因是你的正則表達式的這一部分:

,-: 

它匹配,(ASCII 44)至:(ASCII 58)範圍內的任何字符,其中包含所有數字(包括ASCII 48-57)。

如果你逃跑的-它應該很好地工作,而不是匹配的數字:

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

或將其放在開頭或結尾。 – Braj

+1

'[, - :]'實際上匹配', - 。/0 1 2 3 4 5 6 7 8 9:' –

+0

很好,這就是我一直在尋找的!謝謝 - 我所要做的就是逃避它。我會很快接受你的回答。 – JWizard

相關問題