tags:

views:

106

answers:

5

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
Thanks Bill... was just looking into how to format this.
Tyler Bye
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
@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
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
+1, for thinking outside the box and giving an answer that is easily understood rather that depending on some unnecessary regex.
camickr
Thanks I appreciate it
NickTFried
A: 

Try ^(\d+|\d+\.|\d*\.\d+)[dD]?$

Aaron Digulla
+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
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
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