开发者

How do I make sure a string only a double of any length?

开发者 https://www.devze.com 2022-12-10 10:42 出处:网络
I need a Regex I think to see if a st开发者_高级运维ring is only a double but it can be of any length, any suggestions?Could you try and convert the string to a double and catch the exception if it fa

I need a Regex I think to see if a st开发者_高级运维ring is only a double but it can be of any length, any suggestions?


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
}


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].


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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消