1

Long story short I am checking a rather lengthy error log. I would like to find and parse the ip address associated with each error.

example I want to parse

client: 12.345.678.910

def check_file( file, string )
  File.open( file ) do |io|
    io.each do |line|
      result << parse_ip( line ) if line.include? string
    end
  end
  result
end

def parse_ip( flag )
  flag = flag.split.find_all{|word| /^client:.+/.match word}
  ip = flag. # need to grab ip here
  ip
end

Is there a simple way to get next word?

I am just not sure how to grab the characters following "client:"

Any assistance is appreciated.

EDIT: syntax error

  • There's a regexp for IPv4 addresses in [this answer](http://stackoverflow.com/a/106223/215168) that should be of some use – Abe Voelker May 31 '12 at 18:13

2 Answers2

4

There are several ways to do it. For your example, you could extract the ip with a single regexp capture:

def parse_ip( flag )
  m = /\bclient:\s*([\d\.]+)/.match flag
  m && m[1]
end

If you really prefer to tokenize with split for other reasons, you can use Enumerable#drop_while to scan to the key, then index to the next token:

def parse_ip( flag )
  flag.split.drop_while{|token| token !~ /^client:/}[1]
end
dbenhur
  • 20,008
  • 4
  • 48
  • 45
0
"client: 12.345.678.910"[/client:\s*(.*?)\s*$/, 1]
 => "12.345.678.910" 
Hooopo
  • 1,380
  • 10
  • 16