Skip to content

Instantly share code, notes, and snippets.

@Chryus
Last active December 30, 2015 10:49
Show Gist options
  • Save Chryus/7818687 to your computer and use it in GitHub Desktop.
Save Chryus/7818687 to your computer and use it in GitHub Desktop.
The example below uses regular expressions to parse through a string in timecode format hours:minutes:seconds,milliseconds. The format is used in SubRip (.srt) files to denote the interval of time that a subtitle should appear in a video.
#assign .srt file string to a variable
string = "00:03:10,500 --> 00:00:13,000"
#write regex to betak string into its constitute timecode parts and assign it to var reg_time
#captured data is anything between the parentheses
#'?<>' syntax assigns a key to each snapshot of data, e.g., '?<hour1>' assigns the key hour1
reg_time = /(?<hour1>.*):(?<minutes1>.*):(?<seconds1>.*)--> (?<hour2>.*):(?<minutes2>.*):(?<seconds2>.*)/
#call .match method on reg_time, passing it the string as parameter to retreive the data captures
m = reg_time.match(string)
#returns a MatchData object
=> <MatchData "00:03:10,500 --> 00:00:13,000" hour1:"00" minutes1:"03" seconds1:"10,500 " hour2:"00" minutes2:"00" seconds2:"13,000">
#A MatchData object is sort of like a hash, sort of like an array, but isn't quite either. For example, you can return the value of an index using array bracket notation, but you can't iterate over the object with .each, .select, .collect etc.
#There are three ways you can access the values in a MatchData object.
#1. Call its index, like an array
m[0]
=> "00:03:10,500 --> 00:00:13,000"
#2. Call its assigned key, like a hash
m[:minutes1]
=> "03"
#3. Combine .times with .capture[index] to return values from each index of the MatchData object.
#first get the length of the MatchData object via .length, like an array
number = m.length
=> 7
#next call .times to iterate over each index of the object and return its value.
7.times do |index|
puts "Capture ##{index + 1}: #{m.captures[index]}"
end
=> Capture #1: 00
=> Capture #2: 03
=> Capture #3: 10,500
=> Capture #4: 00
=> Capture #5: 00
=> Capture #6: 13,000
=> Capture #7:
#Finally, expressions evaluated using .match beg to be tested, because if there's no match, the expression returns nil
if m.nil?
puts "There was no match"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment