在使用正则表达式的String中查找多个匹配的索引的问题

时间:2012-12-04 13:36:48

标签: java regex string

我正在尝试使用Regex(下面的测试代码)在String中找到多个匹配的索引,以便与外部库一起使用。

static String content = "a {non} b {1} c {1}";
static String inline = "\\{[0-9]\\}";
public static void getMatchIndices()
{
    Pattern pattern = Pattern.compile(inline);
    Matcher matcher = pattern.matcher(content)
    while (matcher.find())
    {
        System.out.println(matcher.group());
        Integer i = content.indexOf(matcher.group());
        System.out.println(i);
    }
}

输出:

{1}
10
{1}
10

它找到两个组,但两者都返回索引10。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

来自http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String):

  

返回指定子字符串第一次出现的字符串中的索引。

由于两者都匹配相同的东西('{1}'),因此在两种情况下都会返回第一个匹配项。

您可能希望使用Matcher#start()来确定比赛的开始。

答案 1 :(得分:0)

您可以使用regexp执行此操作。以下内容将在字符串中找到位置。

static String content = "a {non} b {1} c {1}";
static String inline = "\\{[0-9]\\}";

public static void getMatchIndices()
{
    Pattern pattern = Pattern.compile(inline);
    Matcher matcher = pattern.matcher(content);

    int pos = 0;
    while (matcher.find(pos)) {
        int found = matcher.start();
        System.out.println(found);
        pos = found +1;
    }
}