整个正则表达式模式的长度

问题描述

我尝试检测一个值是最大长度为10个字符的int还是float。

我最好的解决方法sudo apt install openjdk-8-jre-headless,但10个字符的最大长度不适用于浮点数。

在另一种解决方(^[0-9]{0,10}$|^([0-9]+\.[0-9]+){1,10}$)中,可以使用最大长度,但是如果值以“。”开头或结尾,则正则表达式看起来有效。

如何控制整个图案的长度?

解决方法

在这里我将使用一个替代来覆盖整数(无小数点)和浮点数(有小数点):

^(?:\d{1,10}|(?![\d.]{11,})\d+\.\d+)$

Demo

以下是上述正则表达式的细目分类:

^                   from the start of the input
    (?:\d{1,10}     match 1 to 10 digits,no decimal point
    |               OR
    (?![\d.]{11,})  assert that we DON'T see more than 10 digits/decimal point
    \d+\.\d+)       then match a floating point number (implicitly 10 chars max)
$                   end of the input
,

如果您的正则表达式引擎前瞻性很强,您可以

(?=^.{1,10}$)(^[0-9]+(\.[0-9]+)?$)