Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Predicates to validate if a String contains numeric Value in java

Is the any Predicate Validation in java that checks whether String contains Numbers?

I want to allow special characters but no numbers or spaces. There are Predicates that checks for alphabets but they do they do not allow Special Characters, I need something that only allows alphabets and Special characters and return false if String contains spaces or numericals.

like image 843
Alex Avatar asked Mar 08 '23 06:03

Alex


1 Answers

I will use an regex to show my understanding of the question. You want a Predicate<String> that returns true for any string matching

[a-zA-Z_]*

One way to do this regexlessly is to use a for loop and check each character:

Predicate<String> predicate = x -> {
    for (int i = 0 ; i < x.length() ; i++) {
        if (!Character.isLetter(x.charAt(i)) && !x.charAt(i) == '_') {
            return false;
        }
    }
    return true;
};

Here is a method that does the same thing:

public static boolean test(String x) {
    for (int i = 0 ; i < x.length() ; i++) {
        if (!Character.isLetter(x.charAt(i)) && !x.charAt(i) == '_') {
            return false;
        }
    }
    return true;
}
like image 198
Sweeper Avatar answered Apr 29 '23 21:04

Sweeper