正则表达式只允许 1 到 12 之间的数字

Regex to allow only number between 1 to 12

正则表达式只允许 1 到 12 之间的数字

我正在尝试 (12)|[1-9]\d? 但它不起作用,请帮助我,因为我是正则表达式的新手

尝试这样的事情:

^(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

类似

^([1-9]|1[012])$
  • ^ 将正则表达式锚定在字符串的开头
  • [1-9] 匹配 19

  • |交替,匹配上一场或下一场。

  • 1[012] 匹配 101112
  • $ 将正则表达式锚定在字符串的末尾。

Regex Demo

我认为这应该可行

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

这里有一些现成的正则表达式,适用于一堆不同的 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]

[1-9]|1[012] 适用于贪婪量词(尝试尽可能多地匹配)但不会匹配惰性量词 10,因为一旦它看到 1 就会停止。 Try this at https://regex101.com/

[2-9]|1[012] 将使用惰性量词