我想为浮点数构建一个正则表达式,其中最大长度为6,最多为2个符号。
我想允许任何这些值
XXXXXXX
XXXXX.X
XXXX.XX
XXX.XX
XX.XX
X.XX
我正在尝试这样的\d{1,4}\.?\d{0,2}
,但在这种情况下,我无法输入XXXXX.X
也许我必须使用条件
答案 0 :(得分:3)
我认为XXXX.XX
内的案例是由你的正则表达式处理的。那么为什么不分别匹配其他两种情况(如果你非常热衷于使用正则表达式)。类似的东西:
\d{1,4}\.?\d{0,2} | \d{5}\.?\d |\d{6}
答案 1 :(得分:1)
使用lookahead怎么样:
^(?=\d{1,7}(?:\.\d{0,2})?).{1,7}$
<强> Explannation:强>
The regular expression:
(?-imsx:^(?=\d{1,7}(?:\.\d{0,2})?).{1,7}$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
\d{1,7} digits (0-9) (between 1 and 7 times
(matching the most amount possible))
----------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
\d{0,2} digits (0-9) (between 0 and 2 times
(matching the most amount possible))
----------------------------------------------------------------------
)? end of grouping
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
.{1,7} any character except \n (between 1 and 7
times (matching the most amount possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------