您可以在正向前瞻中使用捕获功能来获取所有重叠的匹配项,并用于
Matcher#start获取捕获的子字符串的索引。
至于正则表达式,它将看起来像
(?=(aa))
在Java代码中:
String s = "aaaaaa";Matcher m = Pattern.compile("(?=(aa))").matcher(s);List<Integer> pos = new ArrayList<Integer>();while (m.find()){ pos.add(m.start());}System.out.println(pos);结果:
[0, 1, 2, 3, 4]
见IDEONE演示



