使用 Java 模式检查是否存在否定列表字符

Checking for Presence of Negative List Characters Using Java Pattern

我似乎在 运行 时被错误地使用表达式抓住了。引起心痛的那一行是

String expression = "$+!*'(),{}|\^[]`<>#%";/?:&=";

这是我的代码

public static boolean hasBlackListCharacters(CharSequence strString)
{
    boolean hasBlackListedChar = false;

    String expression = "$+!*'(),{}|\^[]`<>#%";/?:&=";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(strString);
    if (matcher.matches()) {
        hasBlackListedChar = true;
    }


    return hasBlackListedChar;
}

输入不应匹配以下任何字符。

$+!*'(),{}|\^[]`<>#%";/?:&=

输入字符串

<img src = "http://evil.com">

必须搜索 CharSequence 以查找是否存在这些字符中的任何一个。相应地 return 或 false。

private static Pattern pattern = Pattern.compile("[$+!*'(),{}|\\^\[\]`<>#%\";/?:&=]");

public static boolean hasBlackListCharacters(String strString) {
    return pattern.matcher(strString).find();
}
String expression = "$+!*'(),\{\}|\\^\[\]`<>#%\";/?:&=";

您需要将反斜杠转义两次,因为它在正则表达式中以使其成为正则表达式转义而不是 java excape \ 变成 \\

转义花括号以避免索引异常附近的非法重复

转义方括号。

您还可以查看, https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html#escapeJava(java.lang.String) class 具有强大的转义功能。