Created
November 12, 2012 12:14
-
-
Save higaki/4059045 to your computer and use it in GitHub Desktop.
learn ruby @kof2012 ex1 (regex)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env ruby | |
| # -*- coding: utf-8; -*- | |
| # Ruby初級者向けレッスン KOF出張版 | |
| # 演習問題 1 | |
| # 正規表現を使って <a href="...">...</a> から URL とテキストを抜き出す例 | |
| # %r 記法を使うと、正規表現リテラルの開始・終了文字を自由に選べます。 | |
| # 以下では | を使用しています。 | |
| # \s は空白文字を表し、.*? で href 以外の属性は無視します。 | |
| # 末尾の m は複数行にわたってマッチを試みる指定です。 | |
| # 結果は [[URL, 文字列], [URL, 文字列] ... ] となります。 | |
| # 配列の中に、URL と文字列を格納した配列が複数格納されます。 | |
| def scrape_regex fn | |
| open(fn) do |file| | |
| file.read | |
| .scan(%r|<a\s+.*?href="(.*?)".*?>(.*?)</a>|m) | |
| end | |
| end | |
| # each メソッドで URL と文字列の組を一度に取り出します。 | |
| # " " で囲んだ文字列の中に #{} で囲んだ Ruby の式を書くと | |
| # 文字列として展開されます。 | |
| scrape_regex("rubykansai.html").each do |url, text| | |
| puts "#{text}: #{url}" | |
| end | |
| # 正規表現はややこしいですね。 | |
| # 間違いがあれば、ご指摘ください。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment