Regular expression Range with decimal 0.1 - 7.0

2020-06-16 11:09发布

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.

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?

标签: regex range
2条回答
家丑人穷心不美
2楼-- · 2020-06-16 11:42

To complete the great @TimPietzcker answer,

this Regex...

^(?:7(?:\.0)?|[1-6](?:\.(?:[0-9])?)?|0?(?:\.(?:[1-9])?)?)$

also match:

0
0.
2. 
.2

for anyone who needs it !

查看更多
淡お忘
3楼-- · 2020-06-16 11:47

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

As a one-liner:

^(?:7(?:\.0)?|[1-6](?:\.[0-9])?|0?\.[1-9])$

In Java:

Pattern regex = Pattern.compile("^(?:7(?:\\.0)?|[1-6](?:\\.[0-9])?|0?\\.[1-9])$");
查看更多
登录 后发表回答