2012-07-19 68 views
0

我有一種方法來檢查我的用戶在評論文本字段中的輸入。Java正則表達式匹配

public boolean isValidComment(String commentString) { 
    String expression = "[a-zA-Z0-9_ ]+"; 
    CharSequence inputStr = commentString; 
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); 
    Matcher matcher = pattern.matcher(inputStr); 
    return matcher.matches(); 
} 

這適用於我,但我需要改變我的模式。除了這些字符外,用戶應該能夠鍵入任何字符:<> {} []

如何設置模式以允許除上述之外的所有內容?

+0

你應該用google搜索這個! – user845279 2012-07-19 15:47:58

+0

讓用戶在評論文本字段中輸入他們希望的任何內容,然後確保代碼在將其放入數據庫或網頁之前安全地轉義用戶文本可能會更好。例如,使用<轉義<使其可安全地顯示在網頁上。 – Bobulous 2012-07-19 20:59:27

回答

4

試試這個:

[^\<\>\{\}\[\]]+ 

在ahother手,你需要爲避免使用Pattern恆定重新編譯每次的表達,這樣的事情:

private static final Pattern MY_PATTERN = 
            Pattern.compile("^[^\\<\\>\\{\\}\\[\\]]+$"); 

,並使用常數:

return MY_PATTERN.matcher(commentString).matches(); 
4

[^characters to disallow]

^否定字符類,除了裏面什麼都匹配。

0

尚未測試,但格式爲: 字符串表達式= "[^\\\<\\\>\\\{\\\}\\\[\\\]]+" ^符號適用於所有字符,但以下字符。