Languages
[Edit]
EN

Java - check if string only contains letters

0 points
Created by:
Admin Dirask Community
1420

In this article, we would like to show you how to check if the string only contains letters in Java.

1. Using regex

In this example, we use a regular expression (regex) with Pattern.matcher() to check if the strings contain only letters.

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

public class Example {

    public static void main(String[] args) {
        String letters = "ABCD";
        String numbers = "1234";
        String mixed = "a12b";

        String regex = "^[a-zA-Z]+$";  // regex to check if string contains only letters
        Pattern pattern = Pattern.compile(regex);  // compiles the regex

        // find match between given string and pattern
        Matcher matcherLetters = pattern.matcher(letters);
        Matcher matcherNumbers = pattern.matcher(numbers);
        Matcher matcherMixed = pattern.matcher(mixed);

        // return true if the string matched the regex
        Boolean lettersMatches = matcherLetters.matches();
        Boolean numbersMatches = matcherNumbers.matches();
        Boolean mixedMatches = matcherMixed.matches();

        System.out.println(lettersMatches);     // true
        System.out.println(numbersMatches);     // false
        System.out.println(mixedMatches);       // false
    }
}

Output:

true
false
false

2. Using Character.isLetter()

In this example, we create a function that loops through the string and checks if each character is a letter with Character.isLetter(char ch) method.

Practical example:

public class Example {

    public static void main(String[] args) {
        String letters = "ABC";
        String numbers = "1234";
        String mixed = "1ab2";

        System.out.println(onlyLetters(letters));   // true
        System.out.println(onlyLetters(numbers));   // false
        System.out.println(onlyLetters(mixed));     // false
    }

    public static boolean onlyLetters(String string) {
        if (string == null || string.isEmpty()) {
            return false;
        }
        for (int i = 0; i < string.length(); ++i) {
            if (!Character.isLetter(string.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Output:

true
false
false
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join