From: Gregory Brown Date: 2008-07-31T02:28:09+09:00 Subject: Suggestions for improving a trivial tag parser Hi folks, I need to take strings that have embedded and tags and split them out into an array. Here are some examples: # No need to ensure valid pairs, just need to break out tags from the text #---------------------------------------------------------------------------------------------- describe "Inline style parsing" do it "should return an identical string if inline styles are not detected" do create_pdf @pdf.parse_inline_styles("Hello World").should == "Hello World" end it "should return an array of segments when a style is detected" do create_pdf @pdf.parse_inline_styles("Hello Fine World").should == ["Hello ", "","Fine", "", " World"] end it "should create an array of segments when multiple styles are detected" do create_pdf @pdf.parse_inline_styles("Hello Fine World").should == ["Hello ", "", "Fine ", "", "World", "", ""] end end ### I fear my implementation (below) is showing one of my weakest areas in Ruby, and probably even has some unforeseen problems. I'm sure it can be done more accurately in less code. Any kind RubyTalk folks want to school me? ### def parse_inline_styles(text) #:nodoc: require "strscan" sc = StringScanner.new(text) output = [] last_pos = 0 loop do if sc.scan_until(/<\/?[ib]>/) pre = sc.pre_match[last_pos..-1] output << pre unless pre.empty? output << sc.matched last_pos = sc.pos else output << sc.rest if sc.rest? break output end end output.length == 1 ? output.first : output end ### Thanks, -greg