Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a multidigit number range with Ruby regex?

Tags:

regex

ruby

I'm attempting to match a timecode in the format of "0000" to "2459". How can I match numbers in a specific range, so that I could specifically match all numbers between 0 and 24 and all numbers between 0 and 59, and nothing greater or lesser?

I know how to match each individual digit, but that won't do what I want because for example

/[0-2][0-4]/

would capture numbers 0-4, 10 - 14, and 20-24, missing those in between. So I want to capture all inclusive for multiple digits.

like image 210
Rowhawn Avatar asked Dec 17 '22 17:12

Rowhawn


1 Answers

The following should do the trick:

/(?:[01][0-9]|2[0-4])[0-5][0-9]/

Explanation:

  • The ?: makes the parentheses non-capturing.
  • In the parentheses we simply match either 00-19 or 20-24.
  • After that we match 00-59.
like image 98
Sebastian Paaske Tørholm Avatar answered Jan 04 '23 19:01

Sebastian Paaske Tørholm