I came up with below, this seems to work:
data = <<-EOF Things βββ Foo β βββ 1. Item One β βββ 2. Item Two β βββ 3. Item Three β βββ 4. Item Four β βββ 5. Item Five β βββ 6. Item Six βββ Bar β βββ 1. Item Seven β βββ 2. Item Eight β βββ 3. Item Nine EOF str = "Item One" data.lines.each_with_index do |line, i| if /(?<num>\d)\.\s+#{str}/ =~ line /(?<var>\w+)/ =~ data.lines[i - (n = $~[:num]).to_i] p [n, str, var] # ["1", "Item One", "Foo"] end end
(n = $~[:num]) needed to save the captured num value from
if /(?<num>\d)\.\s+#{str}/ =~ line
into a variable (say n ), since the last matching data represented by the global variable $~ will be overwritten during the next regular expression contained in the statement
/(?<var>\w+)/ =~ data.lines[i - (num = $~[:num]).to_i]
and if we do not save it for later use, we will lose the captured num value.
source share