RegExp range of number (1 to 36)

2020-02-09 07:29发布

I searched a lot and can't find the solution for this RegExp (I have to say I'm not very experienced in Reg. Expressions).

I would like to test a number between 1 and 36, excluding 0 and 37 and above.

What I've got so far and almost works (it doesn't accept 17, 18, 19, 27, 28, 29)...

^[1-9]{1}$|^[1-3]{1}[0-6]{1}$|^36$;

Can someone help me please?

7条回答
放荡不羁爱自由
2楼-- · 2020-02-09 07:43

Try this:

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

(All 1 digit numbers between 1 and 9, all 1x and 2x numbers, and 3x numbers from 30 to 36).

查看更多
聊天终结者
3楼-- · 2020-02-09 07:47

Try this:

/^[1-9]$|^[1-2]\d$|^3[0-6]$/

DEMO

查看更多
乱世女痞
4楼-- · 2020-02-09 07:49

^[0-9]|[0-2][0-9]|3[0-6]$

Here's a breakdown of it:


[0-9] = any digit from 0-9
| = OR
[0-2][0-9] = '1' or '2', followed by any digit from 0-9
| = OR
3[0-6] = '3', followed by any digit from 0-6.

As @mu is too short said, using an integer comparison would be a lot easier, and more efficient. Here's an example function:

function IsInRange(number)
{
    return number > 0 && number < 37;
}
查看更多
看我几分像从前
5楼-- · 2020-02-09 07:49

Try ^[1-9]$|^[1-2]\d$|^3[0-6]$

查看更多
相关推荐>>
6楼-- · 2020-02-09 07:52

I'm not sure why all of the answers to this repeat the mistake of adding boundaries (^ and $) before and after each condition. But you only need to do:

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

I also created a JavaScript/Node.js library, to-regex-range, to simplify creating ranges like this.

查看更多
▲ chillily
7楼-- · 2020-02-09 08:05

You know about \d, right?

^([1-9]|[12]\d|3[0-6])$

Try this in console:

function test() {
    for(var i = 0; i < 100; i++) {
        if (/^([1-9]|[12]\d|3[0-6])$/.test(i.toString()) != (i >= 1 && i <=36)) {
            document.write(i + "fail");
        }
                else
                document.write(i + "pass");
        document.write("<br/>");
    }
}
查看更多
登录 后发表回答