how to check if string contains numbers in Java

In Java, we can determine whether a string contains numeric characters by using Regular Expressions. The following program demonstrates how to verify a string for numeric values using Java with Selenium and TestNG.

Example Script:

import org.testng.Assert;
import org.testng.annotations.Test;

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

public class VerifyStringTest {

@Test
public void testString() {
    String str = "ABC123";

    // Validate string
    Assert.assertNotNull(str, "String should not be null");
    Assert.assertFalse(str.isEmpty(), "String should not be empty");

    // Verify numbers in string
    boolean result = containsNumbers(str);
    Assert.assertTrue(result, "String should contain numbers");
}

public boolean containsNumbers(String str) {
    Pattern pattern = Pattern.compile("\\d");
    Matcher matcher = pattern.matcher(str);
    return matcher.find();
}

}

Explanation:

Class Overview

The VerifyStringTest class is a TestNG test class used to verify whether a given string contains numeric characters.


testString() Method
  • Annotated with @Test, so it is executed by TestNG
  • Initializes a string variable str
  • Uses TestNG assertions to:
    • Ensure the string is not null
    • Ensure the string is not empty
  • Calls the containsNumbers() method to check if the string contains digits
  • Uses Assert.assertTrue() to validate the expected result

containsNumbers(String str) Method

  • Returns a boolean value instead of printing output
  • Uses Regular Expressions (Regex) to detect numbers
  • The pattern \\d matches any digit (0–9)
  • matcher.find() returns:
  • true → if at least one digit is found
  • false → if no digits are found

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x