Regex: how to only allow integers greater than zer

2020-04-08 12:38发布

I have tried the following to only allow integers in my text box, this works great but it allows a zero in there. Is there anything else I can add to prevent a zero being added?

\d+

标签: regex
6条回答
不美不萌又怎样
2楼-- · 2020-04-08 13:05

Code:

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

Example: http://regexr.com/3annd

Tested with:

0
10
01
11
00
1
100
查看更多
beautiful°
3楼-- · 2020-04-08 13:06

A minor variation is this:

/\d*[1-9]\d*/

That would allow leading zeros.

查看更多
三岁会撩人
4楼-- · 2020-04-08 13:13

This will allow 10 but not 01, and it will allow only numbers consisting of digits, i.e., no periods or minus signs...but also no plus signs, scientific notation etc.

^[1-9][0-9]*$
查看更多
乱世女痞
5楼-- · 2020-04-08 13:14
^(\d{2}[1-9])$

matches with: from 001 to 999 example 001 099 999

does not match 000 01 0

查看更多
▲ chillily
6楼-- · 2020-04-08 13:27

If you are not concerned about negatives and silly numbers like 07, this will do:

/[1-9]\d*/

For a more robust solution, I suggest converting the matched string to integer and check if it fulfills your criteria.

查看更多
萌系小妹纸
7楼-- · 2020-04-08 13:32
^(0*[1-9][0-9]*)$

This will allow "silly" numbers like 007 as well, but not 0 or 000 or an empty string.

Note that \d matches also digits from other character sets like ٠١٢٣٤٥٦٧٨٩. See: \d is less efficient than [0-9].

^ denotes the start, $ the end of the string. Together they ensure that the whole string is matched.

查看更多
登录 后发表回答