简体   繁体   English

使用正则表达式匹配到 Java 中的一位小数

[英]Matching to one decimal place in Java using regex

Hopefully a quick question.希望是一个快速的问题。 I'm trying to validate a double.我正在尝试验证双重身份。 Making sure it's positive to one decimal place.确保它是正数到小数点后一位。

Good Values: 0.1, 2.5, 100.1, 1, 54良好值:0.1、2.5、100.1、1、54
Bad Values: -0.1, 1.123, 1.12, abc, 00012.1错误值:-0.1、1.123、1.12、abc、00012.1

So I've tried Regex here:所以我在这里尝试了正则表达式:

 public boolean isValidAge(String doubleNumber)
{
    DoubleValidator doubleValidator = new DoubleValidator();
    return doubleValidator.isValid(doubleNumber,"*[0-9]\\\\.[0-9]");
}

I've also tried: "*[0-9].[0-9]" , "\\\\d+(\\\\.\\\\d{1})?"我也试过: "*[0-9].[0-9]""\\\\d+(\\\\.\\\\d{1})?" , "[0-9]+(\\\\.[0-9]?)?" , "[0-9]+(\\\\.[0-9]?)?"

Nothing seems to be working.似乎没有任何工作。 I've been using org.apache.commons.validator.routines.DoubleValidator我一直在使用org.apache.commons.validator.routines.DoubleValidator

Is there another way I can do this any reason why these regex's aren't working?有没有其他方法可以让这些正则表达式不起作用? I don't have to use regex.我不必使用正则表达式。

Thanks谢谢

This will match a number and only a number with either a multi-digit pre-decimal point number with no leading zero(s), or just a zero, and optionally a decimal point with one decimal digit.这将匹配一个数字,并且仅匹配一个数字,该数字具有一个多位小数点前数字,没有前导零,或者只有一个零,并且可选地是一个小数点和一个小数位。 Includes match of the beginning/end of string, so it won't match a number in a larger string ( updated to not accept leading zeros, credit @Nicklas A ):包括字符串开头/结尾的匹配,因此它不会匹配较大字符串中的数字(更新为不接受前导零,信用@Nicklas A ):

^([1-9]\d*|0)(\.\d)?$

Use the java.util.regex.Pattern library instead.请改用java.util.regex.Pattern库。

http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Because you're putting the regex into a string, be sure to escape the backslashes因为您将正则表达式放入字符串中,所以请务必转义反斜杠

"^([1-9]\\d*|0)(\\.\\d)?$"

I recommend that you read up on regular expressions here, they are an important tool to have "under your belt" so to speak.我建议您在此处阅读正则表达式,可以说,它们是“掌握”的重要工具。

http://www.regular-expressions.info/ http://www.regular-expressions.info/

Pattern.compile ("[0-9]+\\.[0-9])").matcher (doubleNumber).matches ()

would do the trick.会成功的。
If you also want to allow no decimal point:如果您还想不允许小数点:

Pattern.compile ("[0-9]+(\\.[0-9])?").matcher (doubleNumber).matches ()

EDIT: following your comment about no leading zeros and an integer is OK:编辑:按照您关于没有前导零的评论和 integer 可以:

Pattern.compile("([1-9][0-9]*|[0-9])(\\.[0-9])?").matcher(doubleNumber).matches()

if you need to validate decimal with dots, commas, positives and negatives:如果您需要用点、逗号、正数和负数验证小数:

Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+([\\.\\,]{1}[0-9]{1}){0,1}$", (CharSequence) testObject);

Good luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM