1 到 31 之间的正则表达式匹配数,带或不带前导 0

Regex match number between 1 and 31 with or without leading 0

我想在 <input> 上设置一些验证以防止用户输入错误的字符。为此,我使用 ng-pattern。它目前禁止用户输入错误的字符,但我也注意到这不是预期的行为,所以我还计划创建一个指令。


我正在使用

AngularJS: 1.6.1


正则表达式应该匹配什么

以下是正则表达式字符串的要求:

注意事项: 'x' 是可变的,可以是 0 到 100 之间的任何数字。

'x'处的数字是可变的,所以如果可以创建一个易于更改的字符串,我们将不胜感激!


我试过的

我尝试了一些正则表达式字符串,其中:

1) ^0*([0-9]\d{1,2})$

--> Does match 01 but not 1
--> Does match 32 where it shouldn't

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

--> Does match 1 but not 01
--> Does match 32 where it shouldn't

为了测试,我正在使用 https://regex101.com/tests

我在尝试中错过了什么?

这应该有效:

^(0?[1-9]|[12][0-9]|3[01])$

https://regex101.com/r/BYSDwz/1

如果您的目标是匹配 0 到 100,这里有一种方法,基于之前的解决方案。

\b(0?[1-9]|[1-9][0-9]|100)\b

基本上,那场比赛有 3 个部分...

0?[1-9] 通过提及 0 可能存在来解决数字 1 到 9

[1-9][0-9]涵盖数字10到99,[1-9]代表十位

100 封面 100

Here's an example of it

如果要求设置上限为42,表达式的中间部分将变为[1-3][0-9](涵盖10到39),最后部分将变为4[0-2](涵盖40到 42) 像这样:

\b(0?[1-9]|[1-3][0-9]|4[0-2])\b