Regular expression Range with decimal 0.1 - 7.0

混江龙づ霸主 提交于 2019-11-27 23:19:44

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])$");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!