java 正则表达式匹配正值或负值的模式(例如“1.2”、“-2.8”、“7.8”、-22.8)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2856226/
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
RegEx Pattern that matches positive or negative values (e.g "1.2", "-2.8", "7.8", -22.8")
提问by tzippy
decimal seperator is a dot, followed by max one digit! No range specified.
十进制分隔符是一个点,后跟最多一位!没有指定范围。
Thanks guys!
多谢你们!
回答by Artiom Chilaru
^-?\d+(\.\d)?$
if the decimal part is optional, and
如果小数部分是可选的,并且
^-?\d+\.\d$
if it's required :)
如果需要:)
回答by ZyX
Simple: -?\d+\.\d
简单的: -?\d+\.\d
回答by pdbartlett
Unlikely to be relevant in this case, but don't forget that "." is not universal as the decimal separator. Many European countries use "," so you might prefer to get the one in use from the locale:
在这种情况下不太可能相关,但不要忘记“。” 不是通用的小数点分隔符。许多欧洲国家/地区使用“,”,因此您可能更喜欢从语言环境中获取正在使用的那个:
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
String separator = df.getDecimalFormatSymbols().getDecimalSeparator();
(See also: http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormatSymbols.html#getDecimalSeparator)
(另见:http: //java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormatSymbols.html#getDecimalSeparator)

