Languages
[Edit]
EN

Java - check if string contains any letters

0 points
Created by:
Evie-Grace-Noble
351

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

1. Using regex

In this example, we use a regular expression (regex) with Pattern.matcher() to check if the string contains any letters.

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

public class Example {

    public static void main(String[] args) {
        String text = "1ab2";

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

        // find match between given string and pattern
        Matcher matcherText = pattern.matcher(text);

        // return true if the string matched the regex
        Boolean textMatches = matcherText.matches();

        System.out.println(textMatches);  // true
    }
}

Output:

true

2. Using Character.isLetter()

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

Practical example:

public class Example {

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

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

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

Output:

true
false
true
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