Why is this js regex failing to parse a number from 0-23?
pattern = /([0-1]?[0-9]|2[0-3])/
"12".match(pattern) // => matches 12
"23".match(pattern) // => matches 2 (expected 23)
The regular expression returns the first match. The [0-1]?[0-9]
matches 2
.
To get what you want, you need to adjust the order of patterns:
var pattern = /2[0-3]|[0-1]?[0-9]/;
var pattern = /2[0-3]|[0-1]?[0-9]/;
document.write("12".match(pattern));
document.write('<br/>');
document.write("23".match(pattern));
UPDATE
Above will match 234
returning 23
. If you don't want to match it, you can use word boundary \b
, or ^
, $
anchors as Gergo Erdosi suggested:
var pattern = /\b2[0-3]\b|\b[0-1]?[0-9]\b/;
var pattern = /\b(2[0-3]|[0-1]?[0-9])\b/;
Why is this js regex failing to parse a number from 0-23?
Because the first pattern in your regex will always tries to match the input string (ie, the pattern before |
). If it found a match then it won't go for the next pattern (ie, pattern after |
). Your first pattern matches 2
, so it fail to go for the next.
It would work if you reverse the order of the patterns.
OR
Better to use start and end anchors while validating the input string.
> var pattern = /^([0-1]?[0-9]|2[0-3])$/g;
undefined
> "12".match(pattern)
[ '12' ]
> "23".match(pattern)
[ '23' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With