1

I have a MySQL double(10,2) which I've applied the following regex: /^\d{0,10}\.\d{2}$/

I'm not passing validation for 1234, I'm assuming the decimal is required (I understood ? is the optional char which is absent).

Where do I place the ? char in this regex?

thanks

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
erezt
  • 391
  • 4
  • 13

1 Answers1

2

To solve the immediate problem you need an optional group around \.\d{2} pattern - (\.\d{2})?:

/^\d{0,10}(\.\d{2})?$/

It matches 0 to 10 digits from the start of the string and then either requires the end of the string, or . and 2 digits.

Next step, you may allow 1 or 2 digits in the fractional part using a {1,2} limiting quantifier:

/^\d{0,10}(\.\d{1,2})?$/

And even use a non-capturing group to get some very tiny efficiency boost:

/^\d{0,10}(?:\.\d{1,2})?$/
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476