0

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"?

2 Answers 2

1

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

m = fight_info.match(/EnterCombat(.+?)ExitCombat/m)
Sign up to request clarification or add additional context in comments.

3 Comments

Please mark the answer as accepted by clicking the grey arrow so other people know that this question no longer needs an answer.
@blueygh2 The OP accepts an answer only when they think it is the best. It is not done by request. And anyone is free to add an answer before or after an answer is accepted.
@esi You don't have to rush to accept this answer, and you can always change your mind after accepting an answer. Some other answer that you might like better might appear later.
0

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!----- "
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.