Java Regular Expression to check if a String is a numeric value
December 4, 2017
Here is another method from my String utility class. This method uses a regular expression to check if a String is a numeric value.
Look at the code, then read through the explanation that follows
public static boolean isStringANumber(String str) {
String regularExpression = "[-+]?[0-9]*\\.?[0-9]+$";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
Regular Expression Explained:
A String would be a numeric value if it satisfies following conditions:
- [-+]? can begin with an optional + or – sign
- [0-9]* may have any number of digits between 0 and 9.
- \\.? may have a decimal point
- [0-9]$ the String must end with a digit.
A simpler, more reliable way (no regex needed)
This regex doesn’t accept scientific notation (1.5e10), and it silently rejects perfectly valid numbers like Infinity or hex literals. Rather than extending the expression to cover every case Double itself understands, it’s simpler — and more correct — to just let Double.parseDouble do the validation and catch the failure:
public static boolean isStringANumber(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
This has been the more idiomatic approach since long before Java 8, and nothing about it has changed on JDK 21 — it’s included here because the regex version above is still what most people reach for first.