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

编程入门 行业动态 更新时间:2024-10-28 00:29:23
本文介绍了使用正则表达式匹配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.apachemons.validator.routines.DoubleValidator

Nothing seems to be working. I've been using org.apachemons.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 库。

download.oracle/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.

www.regular-expressions.info/

更多推荐

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

本文发布于:2023-11-10 23:02:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数位   正则表达式   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!