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 08:06

Purely for academic reasons, I'll add a unique and accurate pattern.

/^(3[0-6]?|[12]\d?|[4-9])$/

There are three branches in the pattern:

  1. The first matches: 3, 30, 31, 32, 33, 34, 35, 36
  2. The second matches: 1, 2, 10-19, 20-29
  3. The third matches: 4, 5, 6, 7, 8, 9

If there is an efficiency advantage (not that this task is likely to be a major resource drain -- unless you are doing thousands of these evaluations) in my pattern, it will come down to the fact that there are no redundant checks in the pattern.

It may not make any difference to the regex engine, but I've ordered my branches based on the ones that take the least "effort" to evaluate (instead of the natural sequence of numbers).

Harpo's pattern is as brief as the pattern can be built, but [123] are first-digit matches that are satisfied by the multiple branches.

@MichaelHoffmann's and @jonschlinkert's patterns are not correct because they fail to distribute the necessary anchors to each branch. This is concisely achieved by wrapping all branches in a capture group, but as @ninjalj, @qwertymk, and @amit_g demonstrated, it is just as accurate to apply the anchors to each branch.

let txt = '<table border=1 cellpadding=4><tr><th>Number</th><th>Harpo</th><th>Michael Hoffmann</th><th>ninjalj</th><th>jonschlinkert</th><th>qwertymk</th><th>amit_g</th><th>mickmackusa</th></tr>',
    str,
    i;
    
for (i = 0; i <= 40; ++i) {
  str = '' + i;
  txt += '<tr><td>' + i;
  txt += '</td><td>'  + /^([1-9]|[12]\d|3[0-6])$/.test(str);
  txt += '</td><td>' + /^[0-9]|[0-2][0-9]|3[0-6]$/.test(str);
  txt += '</td><td>' + /^[1-9]$|^[1-2][0-9]$|^3[0-6]$/.test(str);
  txt += '</td><td>' + /^[1-9]|[1-2][0-9]|3[0-6]$/.test(str);
  txt += '</td><td>' + /^[1-9]$|^[1-2]\d$|^3[0-6]$/.test(str);
  txt += '</td><td>' + /^[1-9]$|^[1-2]\d$|^3[0-6]$/.test(str);
  txt += '</td><td>' + /^(3[0-6]?|[12]\d?|[4-9])$/.test(str);
  txt += '</td></tr>';
}
txt = txt + '</table>';

document.getElementById('test').innerHTML = txt;
<div id="facts">Correct Pattern Designers: Harpo, ninjalj, qwertymk, amit_g, mickmackussa<br>Incorrect Patterns: Michael Hoffmann, jonschlinkert <br></div>
<div id="test"></div>

查看更多
登录 后发表回答