20

Regex to allow only number between 1 to 12

I am trying (12)|[1-9]\d? but its not working, please help as i am new to regular expression

tanuj shrivastava
  • 722
  • 3
  • 9
  • 21

5 Answers5

39

Something like

^([1-9]|1[012])$
  • ^ Anchors the regex at start of the string
  • [1-9] Matches 1 to 9

  • | Alternation, matches the previous match or the following match.

  • 1[012] Matches 10, 11, or 12
  • $ Anchors the regex at the end of the string.

Regex Demo

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
  • Thank you so much for quick response !! – tanuj shrivastava Sep 07 '15 at 10:07
  • Nice example!!, How could use this with a dynamic value, in the sense maybe it's 30 - 300 or 50 - 3500 etc – Jaison James Jul 23 '18 at 06:45
  • Probably it is better: `^(1[012]|[1-9])$` because so that if it isn't a double digit is for sure a single digit, whereas with the answer, it can find a digit of a double digit. In Python I noticed that for `10` it was returning `1` for example. – roschach Dec 19 '20 at 12:29
27

Here's some readymade regex expressions for a bunch of different numbers within a certain range:

Range Label Regex
1 to 12 hour / month 1[0-2]|[1-9]
1 to 24 hour 2[0-4]|1[0-9]|[1-9]
1 to 31 day of month 3[01]|[12][0-9]|[1-9]
1 to 53 week of year 5[0-3]|[1-4][0-9]|[1-9]
0 to 59 min / sec [1-5]?[0-9]
0 to 100 percentage 100|[1-9]?[0-9]
0 to 127 signed byte 12[0-7]|1[01][0-9]|[1-9]?[0-9]
32 to 126 ASCII codes 12[0-6]|1[01][0-9]|[4-9][0-9]|3[2-9]
KyleMit
  • 30,350
  • 66
  • 462
  • 664
5

Try something like this:

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

1[0-2] : first charcter must be 1 and second character can be in range from 0 to 2

[1-9] : numbers from 1-9

^ : start of string

$ : end of string

Demo

Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
2

[1-9]|1[012] works for greedy quantifiers (that try to match as much as they can) but will not match 10 for lazy quantifiers because as soon as it sees 1 it will stop. Try this at https://regex101.com/

[2-9]|1[012] will work with lazy quantifiers

Erin
  • 21
  • 2
1

I think this should work

\[1-9]|1[0-2]\
Rel
  • 2,494
  • 2
  • 15
  • 15