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

时间:2012-06-08 14:44:49

标签: java regex string

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

E.g。如果我在需要的字符串al中查找模式albala,则值为0.3。

2 个答案:

答案 0 :(得分: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());
    }
}

答案 1 :(得分: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");
    }
}

您可以在Test Harness (The Java Tutorials > Essential Classes > Regular Expressions)

中找到此示例