使用正则表达式获取字符串中模式的索引

2022-08-31 10:05:26

我想在字符串中搜索特定模式。

正则表达式类是否提供字符串中模式的位置(字符串中的索引)?
该模式的出现次数可能超过 1 次。
有什么实际的例子吗?


答案 1

使用匹配器

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());
    }
}

答案 2

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};
}