How to check string contains at least one alphabets in Java


In this post we will learn how to check string contains alphabets/letters using regex (regular expression) in java.

Regular expressions provides one of the simplest ways to find whether string contains at least one alphabets/letters or not in java.

Example >
string 'a123' contains at least one alphabets/letters
string 'abcd' contains at least one alphabets/letters
string '@!ab' contains at least one alphabets/letters



string '1234' doesn't contains any alphabets/letters value
string '@#12!' doesn't contains any alphabets/letters value


Example 1 to check string contains alphabets/letters in java using regex >
regex (Regular Expression) used = ".*[a-zA-Z]+.*"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsAlphabetsExample {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile(".*[a-zA-Z]+.*");
     String str = "a123";
     Matcher matcher = pattern.matcher(str);
     if (matcher.matches()) {
          System.out.println("string '"+str + "' contains at least one alphabets/letters");
     } else {
          System.out.println("string '"+str + "' doesn't contains any alphabets/letters value");
     }
}
}
/*
string 'a123' contains at least one alphabets/letters
*/

No comments:

Post a Comment