双打上的 Java 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14563106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regex on doubles
提问by Duane
I'm trying to check for a double that has a maximum of 13 digits before the decimal point and the decimal point and numbers following it are optional. So the user could write a whole number or a number with decimals.
我正在尝试检查小数点前最多有 13 位数字的双精度数,并且小数点和后面的数字是可选的。所以用户可以写一个整数或一个带小数的数字。
To start with I had this:
首先我有这个:
if (check.matches("[0-9](.[0-9]*)?"))
I've been through several pages on Google and haven't had any luck getting it working despite various efforts. My thought was to do it like this but it doesn't work:
我已经浏览了 Google 上的几页,尽管做出了各种努力,但仍然没有运气让它工作。我的想法是这样做,但它不起作用:
[0-9]{1,13}(.[0-9]*)?
How can I do it?
我该怎么做?
回答by John Kugelman
Don't forget to escape the dot.
不要忘记逃避点。
if (check.matches("[0-9]{1,13}(\.[0-9]*)?"))
回答by Ivaylo Strandjev
First of all you need to escape the dot(in java this would be [0-9]{1,13}(\\.[0-9]*)?
). Second of all don't forget there is also another popular representation of doubles - scientific. So this 1.5e+4
is again a valid double number. And lastly don't forget a double number may be negative, or may not have a whole part at all. E.g. -1.3
and .56
are valid doubles.
首先,您需要转义点(在 Java 中这将是[0-9]{1,13}(\\.[0-9]*)?
)。其次不要忘记还有另一种流行的双打表现——科学。所以这1.5e+4
又是一个有效的双数。最后不要忘记双数可能是负数,或者可能根本没有整个部分。例如-1.3
和.56
是有效的双打。
回答by Trenton D. Adams
John's answer is close. But a '-' needs to be added, in case it's negative, if you accept negative values. So, it would be modified to -?[0-9]{1,13}(\.[0-9]*)?
约翰的回答很接近。但是如果您接受负值,则需要添加一个“-”,以防它是负数。所以,它会被修改为-?[0-9]{1,13}(\.[0-9]*)?
回答by august0490
if you need to validate decimal with commas and negatives:
如果您需要使用逗号和负数来验证小数:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\+\-]{0,1}[0-9]+[\.\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.
祝你好运。
回答by stema
You need to escape the dot and you need at least on digit after the dot
您需要转义点,并且点后至少需要一个数字
[0-9]{1,13}(\.[0-9]+)?
See it here on Regexr
在 Regexr 上看到它