使用正则表达式匹配Java中的一个小数位 [英] Matching to one decimal place in Java using regex

查看:166
本文介绍了使用正则表达式匹配Java中的一个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望是一个快速的问题。我正在尝试验证双倍。确保它对小数点后一位是正的。

Hopefully a quick question. I'm trying to validate a double. Making sure it's positive to one decimal place.

好的值:0.1,2.5,100.1,1,55

错误值:-0.1,1.123 ,1.12,abc,00012.1

Good Values: 0.1, 2.5, 100.1, 1, 54
Bad Values: -0.1, 1.123, 1.12, abc, 00012.1

所以我在这里试过Regex:

So I've tried Regex here:

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

我也试过:* [0 -9]。[0-9]\\\\\\ +(\\\\。\\\ \d {1})?[0-9] +(\\\\。[0-9]?)?

似乎没有任何效果。我一直在使用 org.apache.commons.validator.routines.DoubleValidator

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.

谢谢

推荐答案

这将匹配一个数字,只有一个数字与多位小数点前小数点,没有前导零(s),或只是一个零,以及可选的小数点与一个十进制数字。包括字符串开头/结尾的匹配,因此它与较大字符串中的数字不匹配(更新为不接受前导零,信用@Nicklas A ):

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)?$

请改用 java.util.regex.Pattern 库。

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/

这篇关于使用正则表达式匹配Java中的一个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆