Check if a String Contains a Number Value in Java – 用 Java 检查字符串是否包含数值

最后修改: 2023年 10月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short article, we’re going to highlight how to check if a string contains a number in Java.

在这篇短文中,我们将重点介绍如何在 Java 中检查字符串是否包含数字。

First, we’ll kick things off by considering solutions using JDK. Then, we’re going to illustrate how to achieve the same objective using external libraries such as Guava and Apache Commons Lang.

首先,我们将考虑使用 JDK 的解决方案。然后,我们将说明如何使用 Guava 和 Apache Commons Lang 等外部库来实现相同的目标。

2. Introduction to the Problem

2.问题介绍

Our main goal here is to check if a string contains a number or not. So, the basic idea is to create methods that return true if the given string contains a number, and false otherwise.

我们的主要目标是检查字符串是否包含数字。因此,我们的基本思路是创建这样的方法:如果给定字符串包含数字,则返回 true,否则返回 false

Please note that we’ll work under the assumption that our strings are non-null and non-empty so as to avoid repeating boilerplate code for null and empty checks.

请注意,我们将假设字符串是非空和非空的,以避免重复检查空和空的模板代码。

3. Using the String Class

3.使用 String

The String class comes with a set of handy methods that we can use to check whether a specific string contains a number.

String 类带有一组方便的方法,我们可以用它们来检查特定字符串是否包含数字。

So, let’s take a closer look at each of these methods.

那么,让我们来详细了解一下这些方法。

3.1. String#matches Method

3.1.String#matches 方法

The matches() method is introduced typically to test a string against a regex. As the name implies, it simply checks whether or not a string matches a given regular expression.

matches()方法通常用于根据正则表达式测试字符串。顾名思义,它只是检查字符串是否与给定的正则表达式匹配。

In short, all we need to do is define the right regex that denotes “contains a number”:

简而言之,我们需要做的就是定义表示 “包含数字 “的正确 regex

static boolean checkUsingMatchesMethod(String input) {
    return input.matches(".*\\d.*");
}

In general, we used “.*\\d.*” as regex to denote that the string contains at least one digit. Alternatively, we can replace “\\d” with “[0-9]” as they describe the same thing (digit/number).

一般来说,我们使用 “.*\d.*” 作为 regex 来表示字符串至少包含一位数字。另外,我们可以用 “[0-9]” 替换 “\d”,因为它们描述的是同一件事(数字/数字)

Now, let’s create a test case to unit test our method:

现在,让我们创建一个测试用例,对我们的方法进行单元测试:

public class StrContainsNumberUtilsUnitTest {

    private static final String INPUT_WITH_NUMBERS = "We hope 2024 will be great";
    private static final String INPUT_WITHOUT_NUMBERS = "Hello world";

    @Test
    public void givenInputString_whenUsingMatchesMethod_ThenCheck() {
        assertTrue(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITH_NUMBERS));
        assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITHOUT_NUMBERS));
        assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(""));
        assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(null));
    }

}

3.2. String#replaceAll Method

3.2.String#replaceAll 方法

We can also use the replaceAll() method to address our central question. It returns a string replacing all the characters matching the specified regex.

我们还可以使用 replaceAll() 方法来解决我们的核心问题。它会返回一个字符串,替换与指定 regex 匹配的所有字符

The basic idea here is to use the regex that matches a digit to replace all the numbers in a particular string:

这里的基本思想是使用匹配数字的 regex 来替换特定字符串中的所有数字:

static boolean checkUsingReplaceAllMethod(String input) {
    String result = input.replaceAll("\\d", "");
    return result.length() != input.length();
 }

Here, we replaced all the numbers with a space. As a result, the input contains a number if the length of the returned string is different from the original one.

在这里,我们用空格替换了所有数字。因此,如果返回字符串的长度与原始字符串不同,输入中就会包含一个数字

Please notice that the matches() method provides a more concise and direct manner to address our central question compared to replaceAll().

请注意,与 replaceAll() 方法相比,matches() 方法提供了一种更简洁、更直接的方式来解决我们的核心问题。

Now, let’s add a test case to confirm that everything works as expected:

现在,让我们添加一个测试用例,以确认一切按预期运行:

@Test
public void givenInputString_whenUsingReplaceAllMethod_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(""));
    assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(null));
}

4. Using the Pattern Class

4.使用 Pattern

Similarly, we can use the Pattern class to fulfill the same goal. This class offers a convenient way to compile a regex and match it against a given string.

同样,我们可以使用 Pattern 类来实现相同的目标。该类提供了一种编译 regex 并将其与给定字符串匹配的便捷方法

So, let’s reuse the same regex we already defined in the previous examples:

因此,让我们重复使用之前示例中定义的 regex:

static boolean checkUsingPatternClass(String input) {
    return Pattern.compile(".*\\d.*")
      .matcher(input)
      .matches();
}

In a nutshell, the compile() method lets us create a pattern from the “.*\\d.*” regex. The matcher() method creates a Matcher object that can match our input against the compiled “contains a digit” regex.

简而言之,compile() 方法可以让我们从 “.*\d.*” regex 中创建一个模式。matcher() 方法会创建一个 Matcher 对象,该对象可以将我们的输入与编译后的 “包含一位数字 “的 regex 匹配。

As the name indicates, the matches() method does the job of checking if our input contains a digit.

正如其名所示,matches() 方法的作用是检查输入是否包含数字

Lastly, let’s add another test case for our method:

最后,为我们的方法添加另一个测试用例:

@Test
public void givenInputString_whenUsingPatternClass_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingPatternClass(""));
    assertFalse(StrContainsNumberUtils.checkUsingPatternClass(null));
}

5. Using the Character#isDigit Method

5.使用 Character#isDigit 方法

Another way to check if a string contains a number is to use the Character.isDigit() method, which determines whether a particular character is a digit or not.

检查字符串是否包含数字的另一种方法是使用 Character.isDigit() 方法,该方法可确定特定字符是否为数字。

We can loop through the string and call isDigit() to check if the current character denotes a number:

我们可以在字符串中循环并调用 isDigit() 来检查当前字符是否表示数字:

static boolean checkUsingIsDigitMethod(String input) {
   for (char c : input.toCharArray()) {
      if (Character.isDigit(c)) {
         return true;
      }
   }

   return false;
}

Now, we’ll create a new test case:

现在,我们将创建一个新的测试用例:

@Test
public void givenInputString_whenUsingIsDigitMethod_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(""));
    assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(null));
}

6. Using Stream API

6.使用流应用程序接口

The Stream API provides a convenient way to check if a given string contains a number. Java 8 introduced a new method chars() in the String class. This method returns an IntStream holding the code values of the characters in the given string.

Stream API 提供了检查给定字符串是否包含数字的便捷方法。Java 8 在 String 类中引入了一个新方法 chars() 。该方法返回一个 IntStream ,其中包含给定字符串中字符的代码值。

So, let’s see it in action:

那么,让我们来看看它的实际效果吧:

static boolean checkUsingStreamApi(String input) {
    return input.chars()
      .anyMatch(Character::isDigit);
}

As shown above, we used the anyMatch() method to check whether any of the characters represents a digit.

如上所示,我们使用 anyMatch() 方法来检查是否有任何字符代表数字

As always, let’s add another test case to confirm our new method:

像往常一样,让我们添加另一个测试用例来确认我们的新方法:

@Test
public void givenInputString_whenUsingStreamApi_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingStreamApi(""));
    assertFalse(StrContainsNumberUtils.checkUsingStreamApi(null));
}

7. Using Apache Commons Lang

7.使用 Apache Commons Lang

Moreover, we can use the Apache Commons Lang library to grapple with the key question. However, we need first to add its dependency to our pom.xml:

此外,我们还可以使用 Apache Commons Lang 库来解决关键问题。不过,我们首先需要将其 依赖关系添加到 pom.xml 中:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

This library provides the StringUtils class to achieve string operations in a null-safe manner. The class comes with the getDigits() method, which extracts numbers from a specific string.

该库提供了 StringUtils 类,用于以空安全方式实现字符串操作。该类自带的 getDigits() 方法可从特定字符串中提取数字。

So, let’s see it in practice:

那么,让我们来看看实际操作吧:

static boolean checkUsingApacheCommonsLang(String input) {
    String result = StringUtils.getDigits(input);
    return result != null && !result.isEmpty();
}

As depicted above, getDigits() returns a new string containing only digits. So, all we need to do is check if our returned string is not empty to make sure that our input contains digits.

如上图所示,getDigits() 返回一个仅包含数字的新字符串。因此,我们需要做的就是检查返回的字符串是否为空,以确保我们的输入包含数字

In the usual manner, let’s create a test case:

按照通常的方法,让我们创建一个测试用例:

@Test
public void givenInputString_whenUsingApacheCommonsLang_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(""));
    assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(null));
}

8. Using Guava

8.使用番石榴

The Guava library is another option to consider if we want to check if a given string contains digits. Let’s begin by adding its dependency to our pom.xml:

如果我们要检查给定字符串是否包含数字,Guava库是另一个可以考虑的选择。首先,让我们将其 依赖关系添加到 pom.xml 中:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

Next, let’s see a quick example using the Guava library:

接下来,我们来看一个使用 Guava 库的快速示例:

static boolean checkUsingGuava(String input) {
    String result = CharMatcher.forPredicate(Character::isDigit)
      .retainFrom(input);
    return !result.isEmpty();
}

Guava offers the CharMatcher() class to manipulate characters. Here, we used the forPredicate() method to filter only numbers and return them using the retainfrom() method.

Guava 提供了 CharMatcher() 类来处理字符。在这里,我们使用 forPredicate() 方法仅筛选数字,并使用 retainfrom() 方法返回数字

Finally, we’ll add a new test case for our method:

最后,我们将为我们的方法添加一个新的测试用例:

@Test
public void givenInputString_whenUsingGuava_ThenCheck() {
    assertTrue(StrContainsNumberUtils.checkUsingGuava(INPUT_WITH_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingGuava(INPUT_WITHOUT_NUMBERS));
    assertFalse(StrContainsNumberUtils.checkUsingGuava(""));
    assertFalse(StrContainsNumberUtils.checkUsingGuava(null));
}

9. Conclusion

9.结论

In this tutorial, we explored a variety of ways to check if a string contains numbers in Java.

在本教程中,我们探讨了在 Java 中检查字符串是否包含数字的各种方法。

First, we looked at some ways to achieve this using the JDK. Then, we showcased how to tackle our core challenge using a couple of third-party libraries.

首先,我们了解了使用 JDK 实现这一目标的一些方法。然后,我们展示了如何使用几个第三方库来应对我们的核心挑战。

As always, the code used in this article can be found over on GitHub.

与往常一样,本文中使用的代码可以在 GitHub 上找到