1

I found this from a code challenge:

def time_correct(t)  
  return unless t =~ /^\d{2}(:\d{2}){2}$/
end

it is used to find out whether e.g. "0;:44:07" is a regular time string ("HH:MM:SS") or not. I don't understand the regex though. Can someone explain the /^\d{2}(:\d{2}){2}$/ to me please? Thanks!

Chaoguo0
  • 21
  • 2
  • regex101.com is good resource to learn & understand regex. See [this](https://regex101.com/r/WIH7FL/1). Check the EXPLANATION section on top right. – Tushar Feb 17 '17 at 02:53
  • Aside from the regular expression, can this method return anything other than `nil`? Note the regex matches `'99:99:99'` even though that's not a valid time. What is the URL for the "code challenge" you mention? – Cary Swoveland Feb 17 '17 at 03:48
  • `def time_correct(t) return t if t.nil? || t.empty? return unless t =~ /^\d{2}(:\d{2}){2}$/ t = t.split(":").map(&:to_i) Time.at(t[0] * 3600 + t[1] * 60 + t[2]).strftime "%H:%M:%S" end` that 's the complete code. I only copy and pasted the line that I didn't completely understand. – Chaoguo0 Feb 17 '17 at 05:11

1 Answers1

3

On /^\d{2}(:\d{2}){2}$/:

  1. /.../ delimiters the regex expression.
  2. ^ matches the start of the line, if on multi line mode, or the beginning of the string otherwise.
  3. \d matches one digit
  4. {2} states that the preceding statement \d must match 2 times.
  5. (...) delimiters a capture group. It group things together as the usual math parenthesis concept and also allow you to you refer to them latter using \i, where i is the index of the group. Example, (a)(b), a is the group 1 and b is the group 2.
  6. \d{2} just explained on the steps 3 and 4.
  7. {2} the same as on the step 4, but here the preceding is the capture group (:\d{2}), which must repeat also 2 times.
  8. $ matches the end of the line, if on multi line mode, or the end of the string otherwise.

If the multi line mode is enabled, your expression matches only things like:

22:33:44
02:33:44

But not as

22:33:44 d
d 22:33:44
f 02:33:44 f

If multi line is not enabled, your expression only matches a string containing a valid expression as:

22:33:44

But nothing, on a string with two valid lines:

22:33:44
02:33:44

This is a link for live testing: https://regex101.com/r/cdSdt4/1

Evandro Coan
  • 8,560
  • 11
  • 83
  • 144