Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex failing to parse number from 0-23

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)
like image 644
Shaun Lebron Avatar asked Dec 26 '22 03:12

Shaun Lebron


2 Answers

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/;
like image 177
falsetru Avatar answered Jan 08 '23 09:01

falsetru


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' ]
like image 44
Avinash Raj Avatar answered Jan 08 '23 09:01

Avinash Raj