jurchiks - 8 months ago 61

PHP Question

Is there any way to check for a number in a string within an exact range using purely regex?

What I mean is that I want to check if a string contains a number that ranges, for example, from 1 to 31 in VALUE, not length.

Answer

The numbers of the range from 1 to 31 can be split into two groups: *one digit numbers* (1–9) and *two digit numbers* (10–31). And the latter can further be split into *whole decades* (10–29) and *partial decades* (30–31). These can be expressed as follows:

```
[1-9]|[12][0-9]|3[01]
```

And to match only whole numbers and not just parts of them, you could use look-around assertions:

```
(?<!\d)([1-9]|[12][0-9]|3[01])(?!\d)
```

Here `(?<!…)`

means not preceded by `…`

and `(?!…)`

not followed by `…`

.