6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyでstrscanを使ってiniをパースする

Posted at

実装

require "strscan"

def parse_ini src
  section = { "" => {} }
  current = section[""]
  s = StringScanner.new(src)

  while !s.eos?
    case
    when s.scan(/\s+/)
      # nothing
    when s.scan(/\[(.+?)\]/)
      section[s[1]] = current = {}
    when s.scan(/(\w+)\s*=\s*(["'])?([^\n]+)\2/)
      current[s[1]] = s[3]
    when s.scan(/(\w+)\s*=\s*(\d+\.\d+)/)
      current[s[1]] = s[2].to_f
    when s.scan(/(\w+)\s*=\s*([\d]+)/)
      current[s[1]] = s[2].to_i
    else
      raise "Parse Error. rest=#{ s.rest }"
    end
  end

  return section
end

if $0 == __FILE__
  require "pp"
  pp parse_ini(DATA.read)
end

__END__
piyo = "piyopiyo"

[foo]
name  = "hoge"
age   = 20
point = 10.7

[bar]
hoge = 'hogehoge'

実行結果

% ruby /tmp/aaa.rb
{""=>{"piyo"=>"piyopiyo"},
 "foo"=>{"name"=>"hoge", "age"=>20, "point"=>10.7},
 "bar"=>{"hoge"=>"hogehoge"}}

感想

Rubyでテキストをパースする時はstrscanが本当に便利!
もう正規表現には戻れない。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?