From: Sandro Paganotti Date: 2008-07-03T17:08:31+09:00 Subject: Re: Statistician I (#167) ------=_Part_9174_9250184.1215072698733 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Here's mine solution: (http://pastie.org/226949) class Parse def initialize(rules) @rules = create_rules(rules) end # Read the rules and transform then into regexp def create_rules(rules) rules.collect do |r| vars =[]; r=Regexp.escape(r.chomp).gsub("\\\[","[").gsub("\\\]","]").gsub /\[([^\]]+)\]/, '(?:\1)?'; r.gsub!(/<([^>]+)>/) do vars<<$1; '(.*?)' end [Regexp.new(r),vars] end end # Parse the given file upon the rules created def parse(data) @match =[]; @exceptions=[]; data.each do |l| mdata=nil; @rules.each_with_index{|(r,d),i| break if !((mdata = [i,r.match(l)]) == [i,nil]) } if !mdata[1].nil? @match << ["Rule #{mdata[0]+1}:",*mdata[1].to_a[1..-1]] else @match << ["# No Match"]; @exceptions << l end end; self end #Print results def to_s "#{@match.collect{|m| m.join(" ")}.join("\n")}" + (@exceptions.empty? ? "" : "\n\nUnmatched input:\n#{@exceptions.join("")}") end end # Example of usage puts "#{Parse.new(File.read("rules.txt")).parse(File.read("guardian.txt"))}" On Tue, Jul 1, 2008 at 10:47 PM, benjamin.billian@googlemail.com < benjamin.billian@googlemail.com> wrote: > Added some lines to show the unmatched input. > > http://www.pastie.org/225875 > > -- Rita Rudner - "When I eventually met Mr. Right I had no idea that his first name was Always." ------=_Part_9174_9250184.1215072698733--