Expression expression not working?

I am trying to create a regex expression with this requirement.

Demand:

The maximum length is 5 (incl. Decimal point, if it is a decimal number)

Decimal precession - max. 2 digits (if it is a decimal number).

Number - does not have to be a decimal number (optional)

The code:

<script>
function myFunction() {
   var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
    var num = 12345.52; // i will test here indiffernt ways
    var n = regexp.test(num)
    document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>

The result should look like this:

12345.52 -> It should return false, since the length is 8 inc, but returnstrue

123456.52 → false. I found out that I am d{0,5}looking to decimal

12.45 -> true. Perfect (length 5, precession 2)

12345 → true. Perfect (length 5, precession is not crazy)

I hope to build a regex expression that satisfies all of the above scenarios.

Link: Click here.

+4
1

, lookback.

^(?=.{1,5}$)\d+(?:\.\d{1,2})?$

DEMO

:

  • ^ , .
  • (?=.{1,5}$) , 1 5.
  • \d+ .
  • (?:\.\d{1,2})? .
  • $ , .
+6

All Articles