开发者

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

Bad Values: -0.1, 1.123, 1.12, abc, 00012.1

So I've tried Regex here:

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

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

Nothing seems to be working. I've been using 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):

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

Use the java.util.regex.Pattern library instead.

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/


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:

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜