使用正则表达式查找字符串中多个匹配项的索引出现问题

3

我正在尝试使用正则表达式在字符串中查找多个匹配项的索引(请参考以下测试代码),以便与外部库一起使用。

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个回答

2

完成,谢谢。那个 & indexOf(String regex, int index) 工作了。 - user1875841

0
你可以使用正则表达式来实现这个功能。以下代码将会在字符串中找到对应的位置。
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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接