如何检索字符串中匹配模式的索引



我正在寻找字符串中的模式。该模式可以匹配多次。如何检索每个匹配项的索引?

例如,如果我正在寻找字符串al模式albala需要值 0,3。

import java.util.regex.*;
class TestRegex
{
    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("al");
        Matcher m = p.matcher("albala");
        while(m.find())
            System.out.println(m.start());
    }
}

试试这个:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("al");
    Matcher matcher = pattern.matcher("albala");
    while (matcher.find()) {
        System.out.print("I found the text "");
        System.out.print(matcher.group());
        System.out.print("" starting at index ");
        System.out.print(matcher.start());
        System.out.print(" and ending at index ");
        System.out.print(matcher.end());
        System.out.print(".n");
    }
}

可以在测试工具(Java 教程>基本类>正则表达式)中找到此示例

最新更新