user2410266
user2410266

Reputation: 551

Find certain special characters using regex

I would like to find out if the input fields contains certain special characters such as <(@#$%^&*>. If user input has any of those characters,it should return true.

Example :Robert# ,S%am

public static boolean isInvalidCharacters(String input) throws Exception {
    try {

        Pattern pattern = Pattern.compile("[^<(@#$%^&*>]");
        Matcher matcher = pattern.matcher(input);
        boolean isFound =matcher.find();
        if (!isFound) {
            return true;
        } else {
            return false;
        }
    } catch (Exception err) {
        throw err;
    }

Upvotes: 1

Views: 91

Answers (2)

ray
ray

Reputation: 1690

In your code problem was leading ^ character. You can simplify it furthermore like this,

public static boolean isInvalidCharacters(String input) throws Exception {
    try {
        Pattern pattern = Pattern.compile("[<()@#$%^&*>]");
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    } catch (Exception err) {
        throw err;
    }
}

Note: Logic is invalid if you return true when isFound = false.

Edit

You can simplify further since try-catch block is not necessary.

public static boolean isInvalidCharacters(String input) {
    Pattern pattern = Pattern.compile("[<()@#$%^&*>]");
    Matcher matcher = pattern.matcher(input);
    return matcher.find();
}

Upvotes: 1

vszholobov
vszholobov

Reputation: 2363

Your expression is correct in essence, but it needs to be completed so that it marks not one character, but a string.

Try this regex

^[^<(@#$%^&*>]+$

Demo

Java example

public static void main(String[] args) {
    String input = "abcd\nabcd@";

    Pattern pattern = Pattern.compile("^[^<(@#$%^&*>]+$");
    Matcher matcher = pattern.matcher(input);
    boolean isFound = matcher.find();

    System.out.println(!isFound);
}

Also there is a simple solution without regex

boolean isFound = "<(@#$%^&*>"
        .chars()
        .mapToObj(x -> String.valueOf((char) x))
        .anyMatch(input::contains);

Upvotes: 1

Related Questions