0

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

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

4

2 回答 2

7
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());
    }
}
于 2012-06-08T14:49:04.167 回答
0

试试这个:

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 教程 > 基本类 > 正则表达式)

于 2012-06-08T14:50:53.753 回答