Reputation:
I need a Regex I think to see if a string is only a double but it can be of any length, any suggestions?
Upvotes: 0
Views: 210
Reputation: 80
You might also like to look at the NumberUtils from Apache Commons
http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html
Upvotes: 0
Reputation: 108537
I stole this expression from perldoc faq4 -- "is a decimal number".
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern =
Pattern.compile("^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$");
System.out.println(((Boolean) pattern.matcher("1").find()).toString());
System.out.println(((Boolean) pattern.matcher("1.1").find()).toString());
System.out.println(((Boolean) pattern.matcher("abc").find()).toString());
}
}
Prints:
true
true
false
Upvotes: 0
Reputation: 2392
If I take your meaning correctly, this regular expression might work
"/^[+-]?\d+\.\d+$/"
In English -> A + or - sign (maybe) followed by one or more digits followed by a . (decimal point) followed by one or more digits. This regular expression assumes that numbers are not formatted with commas and also assumes that the decimal separator is a dot which is not true in all locales.
Upvotes: 0
Reputation: 23373
A double would match the following regexp:
^[-+]?\d*\.?\d+([eE][-+]?\d+)?$
Note that for a Java String you would need to escape the backslashes, and that \d
is a shorthand for [0-9]
.
Upvotes: 3
Reputation: 66
Could you try and convert the string to a double and catch the exception if it fails?
try{
Double aDouble = Double.parseDouble(aString);
}catch (NumberFormatException nfe){
// handle it not being a Double here
}
Upvotes: 5