Javaと情熱のあいだ

カステラとドーナツと珈琲

文字列に含まれたURL、URIを取得するサンプル

今回はテキストなどからURLやURIだけを正規表現で取得するサンプルです
取得条件はhttpか、httpsで始まる文字列です。
テキストに複数のURL、URIが存在する場合でもwhileを回すことで取得することができます。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherExample {

    /**
     *
     * 実行
     * @throws Exception 例外
     */
    public void execute() throws Exception {
        final Pattern urlPattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+"
                , Pattern.CASE_INSENSITIVE);

        final Matcher matcher = urlPattern.matcher("こんにちは。このURLはサンプルです" +
            "http://aaa.co.jp/~test/test.pl?dep_id=108&id=108&test.jpg" +
            "こんにちは。このURLはサンプルです。" +
            "http://aaa.co.jp/test/test_img/test.png" +
            "こんにちは。このURLはサンプルです。" +
            "http://www.google.co.jp/search?hl=ja" +
            "こんにちは。このURLはサンプルです。");

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }

}

実行結果はこちら

http://aaa.co.jp/~test/test.pl?dep_id=108&id=108&test.jpg
http://aaa.co.jp/test/test_img/test.png
http://www.google.co.jp/search?hl=ja
(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+jpg

と設定したらjpgファイルのURLだけ取得とか可能です。