Question: I have :

```
^-?[0-9]\d*(\.\d+)?$

```

But need it to allow only up to 3 decimal places. So allowed values are:

```
+10.123

-10.123

10.123

10

+10

-10

10.1

10.12

```

Not allowed:

```
10.1234

10.123%

```

Advice / suggested expression mods appreciated.

Thanks in advance.

Answer: 
In addition to `*` and `+` metacharacters, which specify *unlimited* repetition, regex allows you to place specific limits on the number of matches with the `{a,b}` construct. Here, `a` is the minimum required number of matches, and `b` is the maximum. Both `a` and `b` are *inclusive*.

Since you need to match at least one and at most three digits, you need to replace `\d+` with `\d{1,3}`:

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

```

**Optimization:** With a working regex in hand, you can optimize by replacing `[0-9]` with another `\d`, and "folding" it into `\d*` by using `\d+`:

```
^[+-]?\d+(\.\d{1,3})?$

```
```
^(?!0\d)\d*         
(\.\d{1,4})?$ 

```