Java Regular Expression to check if a String is a number

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:

  1. [-+]? can begin with an optional + or sign
  2. [0-9]* may have any number of digits between 0 and 9.
  3. \\.? may have a decimal point
  4. [0-9]$ the String must end with a digit.


Leave a Reply

Your email address will not be published. Required fields are marked *