Check if String contains Alpha Chars in Java

1
1228

Here we are going to see a code sample which would help to determine if a string contains only alphabets or not. We can also find the number of alphabets it contains. So we will also look at the different ways to find alphabets in String as well as count of alphabets in the String. We have already covered the part where we saw the sample code to check How to check if String contains only numeric in Java. To do so, Java provides regular expressions using java.util.regex.Pattern and java.util.regex.Matcher class.

Complete Code Sample to check if String contains only alphabets

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GoyalsbitStringTesting {
    
    //1. This method would check for the alpha chars in strings
    //2. There have to be fix number of alphabets in the String - For Ex: 5 here 
    public static boolean areAllCharsWay1(String str){
        Pattern p = Pattern.compile("^[a-zA-Z]{5}");
        Matcher m = p.matcher(str);
        boolean b = m.matches();
        return b;
    } 
    
    //1. This method would check for the alpha chars in strings
    //2. There can be any number of alphabets in the String
    public static boolean areAllCharsWay2(String str){
        Pattern p = Pattern.compile("^[a-zA-Z]+");
        Matcher m = p.matcher(str);
        boolean b = m.matches();
        return b;
    } 
    
    //1. This method would check for ONLY 3 alpha chars in strings
    public static boolean areAllCharsWay3(String str){
        Pattern p = Pattern.compile("^[a-zA-Z][a-zA-Z][a-zA-Z]");
        Matcher m = p.matcher(str);
        boolean b = m.matches();
        return b;
    } 
    
    public static void main(String[] args) {
        System.out.println("ABCDE contains 5 chars only : " + areAllCharsWay1("ABCDE"));
        System.out.println("ABCNDDD contains n number of chars : " + areAllCharsWay2("ABCNDDD"));
        System.out.println("ABC contains 3 chars only : " + areAllCharsWay3("ABC"));
    }

}

And the output would be :

ABCDE contains 5 chars only : true
ABCNDDD contains n number of chars : true
ABC contains 3 chars only : true

Whats your way of String Validation? Don’t forget to mention in comments 🙂

1 COMMENT

  1. An outstanding share! I’ve just forwarded this onto a coworker who was conducting a little homework on this.
    And he actually ordered me breakfast because I stumbled upon it for him…
    lol. So let me reword this…. Thanks for the meal!!

    But yeah, thanks for spending the time to talk about
    this matter here on your website.

LEAVE A REPLY