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
\\dmatches any digit (0–9) matcher.find()returns:true→ if at least one digit is foundfalse→ if no digits are found