web-dev-qa-db-ja.com

正規表現を使用して文字列内のパターンのインデックスを取得する

特定のパターンの文字列を検索したい。

正規表現クラスは、文字列内のパターンの位置(文字列内のインデックス)を提供しますか?
パターンは1回以上出現する可能性があります。
実用的な例はありますか?

78
Cratylus

Matcher を使用します。

public static void printMatches(String text, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    // Check all occurrences
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end());
        System.out.println(" Found: " + matcher.group());
    }
}
145
Jean Logeart

jean Logeartからの特別版の回答

public static int[] regExIndex(String pattern, String text, Integer fromIndex){
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {
        return new int[]{matcher.start(), matcher.end()};
    }
    return new int[]{-1, -1};
}
3
Ar maj