Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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文で繰り返す。
 ・最短一致とする為、正規表現に「?」を追加する。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした