esi
esi

Reputation: 3

Extracting text between particular lines from a file in Ruby

I'm trying to read/parse a file and extract lines, starting from a line containing a particular keyword and ending at a line with another keyword. Specifically the file is a video game combat log which contains info for multiple fights. I'm trying to get all the info from the start of each fight (indicated by a line containing "EnterCombat") to the end of each fight (indicated by a line containing "ExitCombat")

------ random line ----------
------ random line ----------
!------ EnterCombat ---------!
!----- Combat Info ----------!
!----- Combat Info ----------!
!----- ExitCombat -----------!
------ random line ----------
!------ EnterCombat ---------!
!----- Combat Info ----------!
!----- ExitCombat -----------!

I'm having trouble figuring out how to get the info for each individual fight. So far I came up with:

def fight
  File.open("combat_log.txt", "r") do |f|
    fight_info = f.read
    m = fight_info.match(/EnterCombat(.*)ExitCombat/m)
  end
end

which gets me all the info between the first line containing "Enter" and the LAST line containing "Exit", but how can I get the info between each individual occurrence of "EnterCombat" and "ExitCombat"?

Upvotes: 0

Views: 205

Answers (2)

sawa
sawa

Reputation: 168249

This:

def fight
  File.read("combat_log.txt") do |s|
    m = s.split(/EnterCombat|ExitCombat/).select.with_index{|_, i| i.odd?}
  end
end

will give:

[
  " ---------!\n!----- Combat Info ----------!\n!----- Combat Info ----------!\n!----- ",
  " ---------!\n!----- Combat Info ----------!\n!----- "
]

Upvotes: 0

blueygh2
blueygh2

Reputation: 1538

Better use + instead of *, and make it non greedy by adding ?:

m = fight_info.match(/EnterCombat(.+?)ExitCombat/m)

Upvotes: 1

Related Questions