javaregexuser-input

Checking for Presence of Negative List Characters Using Java Pattern


I seem to have been caught with the incorrect useage of expression at run time. The line that has been causing the heart burn is

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

This is my code

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;
}

The Input should not match any of the following characters.

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

Input String

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

The CharSequence has to be searched for presence of any of these characters.. and return or false accordingly.


Solution

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