我需要一个正则表达式来验证小数点和范围.总共应存在 3 个数字,包括点,并且值必须大于 0.0.这意味着有效范围是从 0.1 到 7.0.
I need a regular expression that should validate decimal point as well as range. Totally 3 number should be present including dot and the value must be greater than 0.0. That means the valid range is from 0.1 to 7.0.
我使用了以下正则表达式:^\d{1,1}(\.\d{1,2})?$
I used the following regex: ^\d{1,1}(\.\d{1,2})?$
除了范围验证外,它工作正常.我需要改变什么?
It works fine except for the range validation. What do I need to change?
推荐答案正则表达式在验证数字范围方面是出了名的糟糕.但这是可能的.您必须将数字范围分解为这些数字的预期文本表示:
Regexes are notoriously bad at validating number ranges. But it's possible. You have to break down the number range into the expected textual representations of those numbers:
^ # Start of string (?: # Either match... 7(?:.0)? # 7.0 (or 7) | # or [1-6](?:.[0-9])? # 1.0-6.9 (or 1-6) | # or 0?.[1-9] # 0.1-0.9 (or .1-.9) ) # End of alternation $ # End of string作为单行:
^(?:7(?:.0)?|[1-6](?:.[0-9])?|0?.[1-9])$在 Java 中:
Pattern regex = Patternpile("^(?:7(?:\.0)?|[1-6](?:\.[0-9])?|0?\.[1-9])$");更多推荐
正则表达式范围小数 0.1
发布评论