Reputation: 5
I try to detect if a value is an int or float with a max length of 10 characters.
My best solution is (^[0-9]{0,10}$|^([0-9]+\.[0-9]+){1,10}$)
but the max length of 10 characters doesn't work with a float number.
In this other solution {^[0-9]{0,10}$|^[0-9\.]{0,10}$
max length works but the regex appear valid if the value start or end by "."
How I can control the length of entire pattern ?
Upvotes: 0
Views: 940
Reputation: 4013
If your regex engine has positive lookaheads you can do
(?=^.{1,10}$)(^[0-9]+(\.[0-9]+)?$)
Upvotes: 1
Reputation: 520938
I would use an alternation here to cover both integers (no decimal point) and floats (has a decimal point):
^(?:\d{1,10}|(?![\d.]{11,})\d+\.\d+)$
Here is a breakdown of the above regex:
^ 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
Upvotes: 1