我需要一个正则表达式来验证小数点和范围.包括点在内总共应该有 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
发布评论