Reputation: 1433
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.
Upvotes: 2
Views: 2021
Reputation: 256
I use the following, hope it can helps! ;)
/^([1-2]\d|3[01]|[1-9]){1}$/
or also without the "exactly 1", be sure, the round parentheses must be present:
/^([1-2]\d|3[01]|[1-9])$/
Upvotes: 0
Reputation: 146450
It's obviously possible since you can always do this:
/^(1)|(2)|.....|(30)|(31)$/
And I bet the expression can be simplified for exact cases, However, IMHO it's just a way to make code unnecessarily complex to maintain.
I bet you'll enjoy this article: How do I write a regular expression that matches an IPv4 dotted address?
Upvotes: 0
Reputation: 655239
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 …
.
Upvotes: 3