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:
- The first matches: 3, 30, 31, 32, 33, 34, 35, 36
- The second matches: 1, 2, 10-19, 20-29
- 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>