Rowhawn Rowhawn - 4 months ago 18
Ruby Question

How to match a multidigit number range with Ruby regex?

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.

Answer

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.
Comments