Skip to content
Advertisement

How do I white list a phrase before validating it for special characters using Java Regex package

Hey I need to bypass the validation for substring whiteList in the string str but the rest of the string needs to be validated for the special characters ‘<‘, ‘>’, ‘$’, ‘#’, ‘@’.

Assuming that substring is not repeated anywhere else in the main string.

This is the main string String str = "blah blah blah X has paid $8,894 to the shop owner blah blah blah"

This is the sub string "String whiteList = "x has paid $8,894 to the shop owner";

current validation for the main string boolean specialChar = Pattern.compile("<|>|\$|#|@", Pattern.CASE_INSENSITIVE).matcher(str).find();

The substring whiteList contains $ which should not be validated and should return false.

I am looking for a solution using regular expression if its possible. Any help would be greatly appreciated. Thanks~

Advertisement

Answer

Just go around it:

String stringToCheck;
int pos = str.indexOf(whiteList);
if (pos >= 0) {
    stringToCheck =
        str.substring(0, pos) + str.substring(pos + whiteList.length());
} else {
    stringToCheck = str;
}

boolean specialChar =
    Pattern.compile("[<>$#@]").matcher(stringToCheck).find();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement