正規表現でデータを取得

取得したいデータのレコード、フィールドそれぞれの正規表現を定義して値を取得する。レコードとか、フィールドというのは awk に出てくる単語から。なぜか馴染み深いんだよね、awk は。perlruby を使いはじめる前にちょこっと使っていただけなんだけど。

require 'pp'

def capture_regexp(text, opt)
  data = []

# puts "#{opt[:record].class}" => "Regexp"

  text.scan(opt[:record]) { |r|

    item = {}
    opt[:field].each {|key, val| 
      item[key] = r.match(val).to_a[1]
    }

    data.push(item)
  }

  return data
end


if $0 == __FILE__
  text = DATA.read

  data = capture_regexp(text,
    {
      :record => %r{<item>.+?</item>}m,
      :field  =>
      {
        :id      => %r{<id>(.+?)</id>}m,
        :name    => %r{<name>(.+?)</name>}m,
        :date    => %r{<date>(.+?)</date>}m,
        :comment => %r{<comment>(.+?)</comment>}m,
      },
    }
  )

  pp data
end

__END__
<root>
  <record>
    <item>
      <name>user01</name>
      <id>0</id>
      <date>2007/11/25</date>
      <comment>comment01 foobar</comment>
    </item>
    <item>
      <name>user02</name>
      <id>1</id>
      <date>2007/11/28</date>
      <comment>comment02 foobar</comment>
    </item>
    <item>
      <name>user03</name>
      <id>2</id>
      <date>2007/11/30</date>
      <comment>comment03 foobar</comment>
    </item>
  </record>
</root>
  • 実行結果

[{:name=>"user01",
:date=>"2007/11/25",
:comment=>"comment01 foobar",
:id=>"0"},
{:name=>"user02",
:date=>"2007/11/28",
:comment=>"comment02 foobar",
:id=>"1"},
{:name=>"user03",
:date=>"2007/11/30",
:comment=>"comment03 foobar",
:id=>"2"}]