0

I'm trying to find a regular expression for a float with a fixed maximum (for example 4) number of significant figures.

this should match with:

- 123.4
- 12.34
- 1.2
- 223
- 0.1234
- 0.000001234

the problem is that the number of non-zeros before and after the dot has to be at most 4 in total.

I tried to split the problem and found solutions for the cases:

- 0.xxxx
- 0.000xxx
- xxxx

But I didn't find a solution for the case that significant digits are found before and after the dot. (examples: 1.23 2.345 )


update: I think I found a solution:

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

2 Answers2

1
^(?!(?:.*?[1-9]){5,})([-+]?\s*\d+\.?\d*?)$

Try this.This will match only 4 or less significant digits.Do not forget to put flags g and m.See demo.

http://regex101.com/r/hQ1rP0/28

vks
  • 67,027
  • 10
  • 91
  • 124
  • thanks! this is not exactly what I need because for example 122.04 is also matched but has 5 significant digits. But the use of a negative lookahead is a good hint! – user4116042 Oct 07 '14 at 12:49
0

I think you want something like this,

^0*(?:[1-9]\d{0,3})?(?:\.0*(?:[1-9]\d{0,3})?)?$

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274