'How to represent regex number ranges (e.g. 1 to 12)?

I'm currently using ([1-9]|1[0-2]) to represent inputs from 1 to 12. (Leading zeros not allowed.)

However it seems rather hacky, and on some days it looks outright dirty.

☞ Is there a proper in-built way to do it?

☞ What are some other ways to represent number ranges?



Solution 1:[1]

I tend to go with forms like [2-9]|1[0-2]? which avoids backtracking, though it makes little difference here. I've been conditioned by XML Schema to avoid such "ambiguities", even though regex can handle them fine.

Solution 2:[2]

Yes, the correct one:

[1-9]|1[0-2]

Otherwise you don't get the 10.

Solution 3:[3]

Here is the better answer, with exact match from 1 - 12.

(^0?[1-9]$)|(^1[0-2]$)

Previous answers doesn't really work well with HTML input regex validation, where some values like '1111' or '1212' will still treat it as a valid input.

Solution 4:[4]

???? You can use:

[1-9]|1[012]

Solution 5:[5]

How about:

^[1-9]|10|11|12$

Matches 0-9 or 10 or 11 or 12. thats it, nothing else is matched.

Solution 6:[6]

You can try this:

^[1-9]$|^[1][0-2]$

Solution 7:[7]

Use the following pattern (0?[1-9]|1[0-2]) use this which will return values from 1 to 12 (January to December) even if it initially starts with 0 (01, 02, 03, ..., 09, 10, 11, 12)

Solution 8:[8]

The correct patter to validate numbers from 1 to 12 is the following:

(^[1-9][0-2]$)|(^[1-9]$)

The above expression is useful when you have an input with type number and you need to validate month, for example. This is because the input type number ignores the 0 in front of any number, eg: 01 it returns 1.

You can see it in action here: https://regexr.com/5hk0s

if you need to validate string numbers, I mean, when you use an input with type text but you expect numbers, eg: expiration card month, or months the below expression can be useful for you:

((^0[1-9]$)|(^1[0-2]$))

You can see it in action here https://regexr.com/5hkae

I hope this helps a lot because it is very tricky.

Regards.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xan
Solution 2 Ingo
Solution 3 Kimman wky
Solution 4 Pacerier
Solution 5
Solution 6 kennyrocker
Solution 7 gleisin-dev
Solution 8