1

I want to build a regular expression for float number with maximum Length 6 and max 2 symbols after dot.

I Want to allow any of this values

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

I am trying something like this \d{1,4}\.?\d{0,2}, but in this case i cannot type XXXXX.X

Maybe i must to use condition

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
Armen Mkrtchyan
  • 921
  • 1
  • 13
  • 34

2 Answers2

3

I beilive cases within XXXX.XX are handled by your regex. So why not match the other two cases seperately ( if you are so keen on using regex for this). Something like :

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

jester
  • 3,491
  • 19
  • 30
1

How about using 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
----------------------------------------------------------------------
Toto
  • 89,455
  • 62
  • 89
  • 125