4

I want to write a regex to match all positive double numbers with maximum 2 digits after decimal point.

My first approach was this:

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

it works fine for most cases but not for scientific notations, for example 10000000 when it's written as 1.0E7.

I've found an answer here and I made adapted it to my case resulting:

[\\s=]+([+]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d{1,2}))$

but now it returns false for a lot of "good" values.

Any idea how to make it match only positive numerical values with 0 to 2 digits after the decimal point but also the scientific notation of the numbers?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Leo Messi
  • 5,157
  • 14
  • 63
  • 125

2 Answers2

4

You copied the exact regex from the other answer which asked for more requirements i.e. matching equation. Removing those with a bit modification you could try:

^[+-]?\d+(?:\.\d*(?:[eE][+-]?\d+)?)?$

Live demo

revo
  • 47,783
  • 14
  • 74
  • 117
3

Assuming zero is not a positive number, you can use

^(?:0\.(?:0[1-9]|[1-9]\d?)|[1-9]\d*(?:\.\d{1,2})?)(?:e[+-]?\d+)?$

where

  • (?:0\.(?:0[1-9]|[1-9]\d?) matches a positive number smaller than 1 with at most 2 decimal places
  • [1-9]\d*(?:\.\d{1,2})? matches a positive number equal or larger than 1, with optional up to 2 decimal places
  • (?:e[+-]?\d+)?optionally matches the scientific notation

Caveats:

  • no leading zeros allowed
  • no . without decimal places allowed (can be fixed by using \.\d{0,2})
  • more decimal places are possible due to the e-notation (e.g. 1e-3)
  • i-Modifier should be used
  • you might just want to use your languages ability to parse and compare float values

Demo: https://regex101.com/r/ljOaIb/1/

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37