Checking whether a string is number or not can be very useful in certain application. In Java there are various way to check whether a number is a string or not. We can use the Exception , try .. catch block, checking character by character or by using regular expression.
Compared to all the methods, checking whether a string is number or not by using regular expression is basically the easiest.
The comparison is based on pattern matching, regular expression is used to create the pattern and is compared to the string. If the pattern match it will return TRUE, if the pattern mismatch it will return FALSE.
1
2
3
4
5
6
7
8 public static boolean isNumeric(String token) {
String regex,regex1,regex2;
regex = "[-+]?[0-9]+.?[0-9]+";
regex1 = "[-+]?[0-9]+.?";
regex2 = "[-+]?.?[0-9]+";
return token.matches(regex)|token.matches(regex1)|token.matches(regex);
}
}