本文介绍了正则表达式 十进制范围 0.1 - 7.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来验证小数点和范围.包括点在内总共应该有 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 = Pattern.compile("^(?:7(?:\\.0)?|[1-6](?:\\.[0-9])?|0?\\.[1-9])$");

这篇关于正则表达式 十进制范围 0.1 - 7.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:19