Check if String Contains Numbers in Java
- Check if String Contains Numbers in Java
-
Use the
matches()
Method to Check if String Contains Numbers in Java -
Use the
replaceAll()
Method to Check if String Contains Numbers in Java -
Use the
isDigit()
Method to Check if String Contains Numbers in Java - Conclusion

This article discusses the various ways to find a number from a string in Java.
Check if String Contains Numbers in Java
In Java, a string is simply a sequence of characters or an array of characters. However, it can contain numeric values too. A string looks like this.
String a = "Hello World!";
If we put in some numeric values, the string will look like this.
String a = "This is 123";
Note that putting numeric values in a string is not illegal. Look at the below program, for example.
import java.util.*;
public class Demo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Asking for a string input
System.out.println("How may we help you?");
String a = sc.nextLine();
System.out.println("Okay, thank you!");
}
}
Output:
How may we help you?
Find the cube of 10
Okay, thank you!
Note that the program runs fine even though the user had input a numeric value inside the string. But this leads to situations where we might need to find out if a number is present in a string or not.
This article will look at a few ways to do that.
Java has a class, the Java String
class, which has a lot of methods to manipulate Java strings in different ways. To find out the presence of a number in a string, we can use some of the built-in methods provided by the Java library.
But before we start, as a prerequisite, we must also know about regex
or regular expressions
. Regex or Regular expressions is an API that helps edit, change, or manipulate strings in Java. It works based on string patterns.
Regex is mainly used to validate email addresses and check if a password meets the basic constraints. The java.util.regex
package helps with regular expressions.
This package has three main classes for different purposes.
util.regex.Pattern
: This is used for defining string patternsutil.regex.Matcher
: This uses patterns to perform matching operationsPatternSyntaxException
: This indicates any syntax error present in a regular expression
To know more about regex and patterns in Java, refer to this documentation.
Use the matches()
Method to Check if String Contains Numbers in Java
The java string matches()
method checks if a string matches the given regular expression. We can use it in two different ways.
string.matches(regex)
Or
Pattern.matches(regex, string)
We get the same result by using either of the above ways. Let us look at an example.
import java.io.*;
public class Demo {
public static void main(String args[]) {
String Str = new String("We will learn about regular expressions");
System.out.println(Str.matches("(.*)regular(.*)"));
System.out.println(Str.matches("expressions"));
System.out.println(Str.matches("We(.*)"));
}
}
Output:
true
false
true
You must wonder that although the word expressions
is present in the string, the output we get is false. We use a period and an asterisk in the other two patterns.
The use of a period .
will match any character but not a newline character. For example, .article
match particle
but not article
.
The asterisk *
, on the other hand, is used to repeat expressions. To match a series of zero or more characters, we use the .*
symbol.
Let us see how we can find if a string has a number.
import java.io.*;
public class Demo {
public static void main(String args[]) {
String Str = new String("The string has the number 10.");
//Using regular expressions
System.out.println(Str.matches("(.*)10(.*)"));
}
}
Output:
true
Note that we changed the last line and still get the same output. Here, the .*
finds the occurrence of a character from 0 to infinite.
Then the double backslash escapes the second backslash to find a digit from 1 to infinite times.
We can also replace the \\d
with [0-9]
. Look at the code for demonstration.
import java.io.*;
public class Demo {
public static void main(String args[]) {
String Str = new String("The string has the number 10.");
System.out.println(Str.matches(".*[0-9].*"));
}
}
Output:
true
All these methods return the result only in Boolean values. Other ways can give the number as output.
To learn more about the matcher class in Java, refer to this documentation.
Use the replaceAll()
Method to Check if String Contains Numbers in Java
This method gives not just one but all the numbers present in a string. Here, we follow a three-step approach.
First, we replace the non-numeric characters with a space. Next, we merge consecutive spaces to one space, and lastly, we discard the trailing spaces such that the remaining string contains only numbers.
public class Demo{
static String FindInt(String str)
{
//First we replace all the non-numeric characters with space
str = str.replaceAll("[^\\d]", " ");
//Remove all the trailing spaces
str = str.trim();
//Replace consecutive white spaces with one white space
str = str.replaceAll(" +", " ");
if (str.equals(""))
return "-1";
return str;
}
public static void main(String[] args)
{
String str = "gibberish123gibberish 456";
System.out.print(FindInt(str));
}
}
Output:
123 456
We use the replaceAll()
method, which takes the regex string and the replacement string. It returns a string replacing the characters that match the regex and replacement string.
Syntax:
string.replaceAll(String regex, String replacement)
Then we use the trim()
method to discard the leading and trailing spaces. Java does that with the help of the Unicode value of space \u0020
.
Note that the trim()
method does not remove the spaces between the string. It only checks for the spaces at the string’s ending and starting.
Syntax:
string.trim()
Use the isDigit()
Method to Check if String Contains Numbers in Java
To find an integer from a string, we can use this in-built function called isDigit()
. But before this, we have to convert the string to a character array. Look at the example.
public class Demo {
public static void main(String args[]){
String example = "Find the square of 10";
char[] ch = example.toCharArray();
StringBuilder strbuild = new StringBuilder();
for(char c : ch){
if(Character.isDigit(c)){
strbuild.append(c);
}
}
System.out.println(strbuild);
}
}
Output:
10
We first use the toCharArray()
method to convert the string to an array of characters. The length of the newly allocated array and the previous string is the same.
Syntax:
string.toCharArray()
Then, we can use the isDigit()
method on each element in the array to find if the string has any numbers.
Conclusion
In this article, we saw how to find a number from a string in Java. To do this, we can use regex in many ways. But regex gives the output as a Boolean value.
To get the output as a number, we can use the replaceAll()
method with the trim()
method. We can also use the Java isDigit()
method to find numbers from a string.
Related Article - Java String
- Perform String to String Array Conversion in Java
- Remove Substring From String in Java
- Convert Byte Array in Hex String in Java
- Convert Java String Into Byte
- Generate Random String in Java
- The Swap Method in Java