我正在尝试使用正则表达式(下面的测试代码)在字符串中查找多个匹配项的索引,以与外部库一起使用。
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。有什么想法吗?
最佳答案
来自 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String ):
Returns the index within this string of the first occurrence of the specified substring.
因为两者都匹配相同的东西('{1}'),所以在这两种情况下都会返回第一次出现的地方。
您可能想使用 Matcher#start()确定比赛的开始。
关于java - 使用正则表达式在字符串中查找多个匹配项的索引的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13704200/