1

我想为浮点数构建一个正则表达式,最大长度为 6,点后最大为 2 个符号。

我想允许任何这些值

XXXXXXX
XXXXX.X
XXXX.XX
XXX.XX
XX.XX
X.XX

我正在尝试这样的事情\d{1,4}\.?\d{0,2},但在这种情况下我无法输入XXXXX.X

也许我必须使用条件

4

2 回答 2

3

我相信其中的案例XXXX.XX由您的正则表达式处理。那么为什么不单独匹配其他两种情况(如果您如此热衷于为此使用正则表达式)。就像是 :

\d{1,4}\.?\d{0,2} | \d{5}\.?\d |\d{6}

于 2013-11-07T08:11:10.683 回答
1

如何使用前瞻:

^(?=\d{1,7}(?:\.\d{0,2})?).{1,7}$

说明:

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
----------------------------------------------------------------------
于 2013-11-07T08:30:05.757 回答