Close

Java Regex to check if the entire string is numeric

[Last Updated: Jan 24, 2017]

Java Regex 

This regex pattern can be used to find if the given string is a number or not.

Pattern

^[-+]?\d*\.?\d+$
^[-+]?Starts with zero or one '-' or '+'
\\d*zero or more digits
\\.?zero or one decimal
\\d+$must end with at least one digit


Example

package com.logicbig.example;


import java.util.regex.Pattern;

public class NumberRegex {
private static final Pattern PATTERN = Pattern.compile("^[-+]?\\d*\\.?\\d+$");

public static void main (String[] args) {
check("3.43");
check("3.4.3");
check(".4");
check("..4");
check("4.");
check("4");
check("-4");
check("-+4");
check("1,222.3");
}

public static boolean isNumber (String str) {
return PATTERN.matcher(str)
.matches();
}

private static void check (String s) {
System.out.printf("%s %s%n", s, isNumber(s));
}
}

Output:

3.43  true
3.4.3 false
.4 true
..4 false
4. false
4 true
-4 true
-+4 false
1,222.3 false



See Also