[英]How do I make sure a string only a double of any length?
我需要一个正则表达式,我想看看一个字符串是否只是一个双精度数,但它可以是任意长度,有什么建议吗?
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: 一个double将匹配以下正则表达式:
^[-+]?\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]
. 请注意,对于Java字符串,您需要转义反斜杠,并且\\d
是[0-9]
的简写。
You might also like to look at the NumberUtils from Apache Commons 您可能还想看看Apache Commons的NumberUtils
http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html
尝试^(\\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 . 用英语-> A +或-符号(可能),然后是一个或多个数字,然后是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". 我从perldoc faq4窃取了这个表达式-“是一个十进制数字”。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.