[英]Java Regular Expression Matches
我有一種方法可以檢查用戶在注釋文本字段中的輸入。
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();
}
這對我有用,但是我需要更改模式。 用戶應該能夠鍵入以下字符以外的任何字符: <> {} []
。
如何設置模式以允許除上述之外的所有內容?
[^characters to disallow]
。
^
否定字符類,匹配除內部內容外的任何其他字符。
嘗試這個:
[^\<\>\{\}\[\]]+
另一方面,您需要使用一個Pattern
常量來避免每次都重新編譯該表達式,如下所示:
private static final Pattern MY_PATTERN =
Pattern.compile("^[^\\<\\>\\{\\}\\[\\]]+$");
並使用常量:
return MY_PATTERN.matcher(commentString).matches();
尚未測試,但格式為:字符串表達式= "[^\\\\\\<\\\\\\>\\\\\\{\\\\\\}\\\\\\[\\\\\\]]+"
^符號適用於所有字符但是以下幾個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.