2010年12月19日

ファイルからURLを抽出するいい加減なRubyソース

個人的に良く使う処理なので貼っておく。かなりいい加減。気が向いたらちゃんと書く。

そういえばRubyのURLって新しいRFC使ってたっけ。URI.parseすると現行で使われているURLも弾いたりする。

def make_url_list( file_path )
  File.open(file_path) { | in_file |
    while line = in_file.gets
      next unless line =~ /(https?\:\/\/[\w\d\@\;\(\)\~\_\\\-\.]+\/[\w\d\:\#\@\%\/\;\$\(\)\~\_\?\\\+\-\=\.\&]*)/
      begin
        URI.parse($1)
      rescue
        next
      end;
      puts $1
    end
  }
end