Languages
[Edit]
EN

Java - check if string contains any numbers

0 points
Created by:
Kourtney-White
635

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

Practical example

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

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

public class Example {

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

        String regex = ".*\\d.*";  // regex to check if string contains any numbers
        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.isDigit()

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

Practical example:

public class Example {

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

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

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

Output:

false
true
true
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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