添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Strings are widely used in the field of programming to store user-provided and calculated data. The String can be a combination of characters, numbers, or both. When taking data from the user, that data is validated to ensure that user-provided String data contains only characters or a combination of numbers. This is important in ensuring the correctness and integrity of the application.

This guide explains the procedure to check if a String contains Numeric values in Java.

How to Check if a String is Numeric in Java?

The String can be checked for numeric values using several approaches like the “regex expression”, “isDigit()” method, and Stream API methods. Moreover, the user can utilize the methods offered by Apache Commons Lang3 Library like “NumberUtils.isCreatable()” and “StringUtils.isNumeric()”.

Let’s implement each approach to check if the provided String holds a Numeric value or not. In addition, at the bottom of this guide, the comparison of all methods according to their average execution time is performed. That comparison helps you choose which method is perfect for you.

Method 1: Check if a String is Numeric Using Regex Expression

The regular expressions are different patterns that are set up according to the requirements to match and manipulate text. The String compares with the stored pattern to check whether the String contains the element that matches the pattern or not. This pattern-matching operation is done using the “ matches() ” method. Let’s apply the regex expression approach to our requirement:

public class StringContainsNumber {
public static void RegexMethod(String input) {
  if (input.matches(".*\\d.*")) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";
  RegexMethod(sampleString);
  RegexMethod(sampleString1);
  RegexMethod(sampleString2);
  RegexMethod(sampleString3);
  RegexMethod(sampleString4);

The description of the above code is as follows:

public static boolean isDigitMethod(String input) {   for (char chars : input.toCharArray()) {   if (Character.isDigit(chars)) {     return true;   return false; public static void main(String[] args) {   String sampleString = "-Hello456World";   String sampleString1 = "Wassap";   String sampleString2 = "";   String sampleString3 = "   ";   String sampleString4 = "0.245";   System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString));   System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString1));   System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString2));   System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString3));   System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString4));

In the above code block:

public static void isDigitMethod(String input) {   if (input.chars().anyMatch(Character::isDigit)) {   System.out.println("The String '" + input + "' Contains Numbers.");   else {   System.out.println("No Numbers Found in the '" + input + "' String"); public static void main(String[] args) {   String sampleString = "-Hello456World";   String sampleString1 = "Wassap";   String sampleString2 = "";   String sampleString3 = "   ";   String sampleString4 = "0.245";   isDigitMethod(sampleString);   isDigitMethod(sampleString1);   isDigitMethod(sampleString2);   isDigitMethod(sampleString3);   isDigitMethod(sampleString4);

In the above code block:

The “Pattern” and “Matcher” classes of “regex” allow us to perform the regular expression approach but in a more optimized and customized manner. These classes offer the “compile()” and “matcher()” methods respectively to save the provided pattern and compare it with provided String characters:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsNumber {
public static void PatternMatcherMethod(String input) {
  Pattern patternObj = Pattern.compile(".*\\d.*");
  Matcher matcherObj = patternObj.matcher(input);
  boolean checker = matcherObj.matches();
  if (checker) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";
  System.out.println("Via 'Pattern' and 'Matcher' Methods");
  PatternMatcherMethod(sampleString);
  PatternMatcherMethod(sampleString1);
  PatternMatcherMethod(sampleString2);
  PatternMatcherMethod(sampleString3);
  PatternMatcherMethod(sampleString4);

The above code works like this:

Another approach to check the existence of numeric digits in the String is using the combination of “replaceAll()” and “isEmpty()” methods. The “replaceAll()” accepts regular expression and value as the first and second parameters. By using this method, the user can remove all non-numeric digits and then check whether there are any remaining digits or not. If yes, then the String contains numeric digits and vice versa:

public class StringContainsNumber {
public static void replaceAllMethod(String input) {
  String pattern = input.replaceAll("\\D", "");
  boolean checker =  pattern.isEmpty();
  if (!checker) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassup";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";
System.out.println("Via 'replaceAll()' Method:\n");
  replaceAllMethod(sampleString);
  replaceAllMethod(sampleString1);
  replaceAllMethod(sampleString2);
  replaceAllMethod(sampleString3);
  replaceAllMethod(sampleString4);

The above code works like this:

The “NumberUtils” class offers two methods that help in finding the existence of numeric values inside the String namely “isCreatable()” and “isParsable()”. The “isCreateable()” is considered a better option because of its minimum average compilation time. Moreover, it provides comparatively better results when the data contains lots of numeric digits, decimal digits, or null values. On the other hand, the “isParseable()” method has less average time with both easy and complex data sets.

To use both methods, the user must add the below dependencies inside the “pom.xml” file. This file is auto-created during the creation of a Java “Maven” project:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

Once added, let’s implement both methods:

public class StringContainsNumber {
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassup";
  String sampleString2 = "65";
  String sampleString3 = "0xA10";
  String sampleString4 = "0.245";
  System.out.println("\nVia 'NumberUtils.isCreatable()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString4));
  System.out.println("\nVia 'NumberUtils.isParseable()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString4));

In the above code block:

The “isNumeric()” method extracts the numeric digits from the String and converts them into a corresponding Unicode representation. Once converted, the method will return true or false accordingly. Moreover, it also throws “false” for the negative and decimal numbers.

The “isNumericSpace()” method is an extended or inherited form of the “isNumeric()” method. As an addition, it checks for the empty spaces in the String and between the String characters. It returns “true” if the String contains only empty spaces or if the digits are separated by a space like “6 7”.

Let’s implement both methods in a single Java program for a better working comparison:

public class StringContainsNumber {
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "-67";
  String sampleString2 = "67";
  String sampleString3 = "0xA10";
  String sampleString4 = "0.245";
  String sampleString5 = " ";
  System.out.println("\nUsing 'StringUtils.isNumeric()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString4));
  System.out.println("Is '" + sampleString5 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString5));
  System.out.println("\nUsing 'StringUtils.isNumericSpace()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString4));
  System.out.println("Is '" + sampleString5 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString5));

In the above code block, multiple Strings are created and passed into the “isNumeric()”, and “isNumericSpace()” methods of the “StringUtils” class. The result obtained by invoking each method is then displayed on the console.

Output

The generated output shows the result obtained by the utilization of both methods of the “StringUtils” class:

Now, the result after increasing the complexity of data sets by including more numeric digits, decimal, and negative values is shown below:

MethodModeExecution Time/ScoreError
RegularExpressionsavgt7168.761± 344.597
CoreJavaavgt10162.872± 798.387
NumberUtils.isCreatableavgt1703.243± 108.244
NumberUtils.isParsableavgt1589.915± 203.052
StringUtils.isNumericavgt1071.753± 8.657
StringUtils.isNumericSpaceavgt1157.722± 24.139

The above benchmarks show that the best methods are the ones provided by Apache Commons Lang. They offer greater flexibility while providing the most optimized result in a minimum execution period. So, one should use these methods to check the existence of numeric digits in a String.

Important: Other than these methods, there exist some other well-known Plain Java methods to check the numeric strings. Read the linked guide to learn more about these methods. 

That’s all about checking the Numeric digits in a String.

Conclusion

There are several approaches to checking the existence of numeric values inside the provided String. These methods are “isDigit()”, “anyMatch()”, “replaceAll()”, “Compile()” and “Matcher()”. The user can also use the following methods namely “NumberUtils.isCreatable()”, “NumberUtils.isParsable()”, “StringUtils.isNumeric()”, and “StringUtils.isNumericSpace()”. These methods are provided by the Apache Commons Lang3 Library and they offer the minimum execution time while maximizing the flexibility.