2013-04-09 139 views
2

我想在JTextField上運行驗證檢查以確保它只包含字母。什麼是最簡單的方法來做到這一點?如何檢查一個字符串是否是純字母?

+1

正則表達式。 – jonny2k9 2013-04-09 21:36:15

+0

另請參見['DocumentListener'](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html)&['JFormattedTextField'](http:// docs .oracle.com/JavaSE的/ 7 /文檔/ API /的javax /擺動/ JFormattedTextField.html)。 – 2013-04-10 00:10:32

回答

4

您可以使用matches

str.matches("\\p{Alpha}+") 

注意\p{Alpha}匹配任何字母(a-zA-Z),因此\p{Alpha}+匹配任何字母連續字符串。

+0

這是否適用於unicode? – MStodd 2013-04-09 21:40:34

+0

這看起來非常簡潔,因此非常適合我的需求。我在哪裏可以瞭解更多關於「\\ p {Aplha} +」語法的內容,以便我能夠理解這一切實際上意味着什麼?我可以複製和粘貼,但我不會真的能夠學習。 – Mike 2013-04-09 21:58:54

+0

@Mike ['Pattern'](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)類的文檔包含一些特定信息,但您可能會想查找關於「正則表達式」的教程。 – arshajii 2013-04-09 22:38:55

1

試試這個:

public boolean containsOnlyLetters(String s) 
{ 
    for(char c : s.toCharArray()) 
    { 
     if(!Character.isLetter(c)) 
      return false; 
    } 
    return true; 
} 
相關問題