I need a Regex I think to see if a string is only a double but it can be of any length, any suggestions?
+5
A:
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
}
Tyler Bye
2009-10-28 15:53:14
Thanks Bill... was just looking into how to format this.
Tyler Bye
2009-10-28 15:56:30
Generally I consider this an anti-pattern (trying something and then catching the exception if it doesn't work). But I don't know why -- it's perfectly valid -- I just try to avoid doing it where possible. Unfortunately I don't think there's a better test here.
Tenner
2009-10-28 16:00:10
@Tenner you should consider it an anti-pattern, since it means catching exceptions for the purpose of program flow. But I blame the API developers for not including a Double.tryParseDouble() method
matt b
2009-10-28 16:03:42
The reason why, is partly due to performance reasons (the time it takes to generate an Exception's stacktrace is nontrivial) and partly conceptual - exceptions should represent *exceptional* circumstances. Thus it's OK if the input *must* be a double, but not if a non-numeric string counts as a valid input.
Andrzej Doyle
2009-10-28 16:05:02
+1, for thinking outside the box and giving an answer that is easily understood rather that depending on some unnecessary regex.
camickr
2009-10-28 17:38:38
Thanks I appreciate it
NickTFried
2009-10-30 21:21:49
+3
A:
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].
rsp
2009-10-28 15:56:38
A:
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.
John Scipione
2009-10-28 16:01:19
A:
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
Mark
2009-10-28 16:06:56