LoginSignup
2
2

More than 5 years have passed since last update.

JAVAで、あるワードが含まれる文字列を区切り文字のブロックごと取得する方法のメモ

Last updated at Posted at 2016-07-21

例えばスクレイピングをするときで、あるワードが含まれる要素をタグ文字ごと取得したい場合のメモです。

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

    /*
     *対象のワードが含まれた、区切り文字で囲まれた文字列を取得するメソッド
     * @param target 全ての文字が含まれる文字列。
     * @param searchKeyWord 検索対象の文字。
     * @param kugiriStartWord 区切りの始まりを示す文字。
     * @param kugiriEndWord 区切りの終わりを示す文字。
    */
    public static String getKugiriBlock (String target , String searchKeyWord , String kugiriStartWord, String kugiriEndWord) {
        // 正規表現の設定
        String regex = kugiriStartWord + ".*?" + searchKeyWord + ".*?" + kugiriEndWord;
        Pattern ptrn = Pattern.compile(regex);
        Matcher matcher = ptrn.matcher(target);

        // 正規表現の検索
        matcher.find();

        // 対象の文字列を含む区切りを返す
        return target.substring(matcher.start() ,matcher.end());

    }

特記事項

 ・複数のブロックを取得したい場合は、matcher.find()をwhile文で繰り返す。
 ・最短一致とする為、正規表現に「?」を追加する。

2
2
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
2
2