在Java中查找字符串中出现的所有子字符串

我试图在Java中查找字符串中所有出现的子字符串。

例如:搜索“ababsdfasdfhelloasdf”为“asdf”将返回[8,17],因为有2个“asdf”,一个位于8位,一个位于17位。搜索“aaaaaa”中的“aa”将返回[0,1, 1,2,3,4]因为在位置0,1,2,3和4处有一个“aa”。

我试过这个:

public List findSubstrings(String inwords, String inword) { String copyOfWords = inwords; List indicesOfWord = new ArrayList(); int currentStartIndex = niwords.indexOf(inword); int indexat = 0; System.out.println(currentStartIndex); while (cthing1 > 0) { indicesOfWord.add(currentStartIndex+indexat); System.out.println(currentStartIndex); System.out.println(indicesOfWord); indexat += cthing1; copyOfWords = copyOfWords.substring(cthing1); System.out.println(copyOfWords); cthing1 = copyOfWords.indexOf(inword); } 

这个问题可以在Python中解决如下:

 indices = [m.start() for m in re.finditer(word, a.lower())] 

“word”是我正在寻找的单词,“a”是我正在搜索的字符串。

我怎样才能在Java中实现这一目标?

您可以在正向前瞻中使用捕获来获取所有重叠匹配,并使用Matcher#start来获取捕获的子串的索引。

至于正则表达式 ,它看起来像

 (?=(aa)) 

在Java代码中:

 String s = "aaaaaa"; Matcher m = Pattern.compile("(?=(aa))").matcher(s); List pos = new ArrayList(); while (m.find()) { pos.add(m.start()); } System.out.println(pos); 

结果:

 [0, 1, 2, 3, 4] 

请参阅IDEONE演示

使用正则表达式对于查找子字符串来说绝对是一个过于繁重的解决方案,如果你的子字符串包含特殊的正则表达式字符,那么它尤其会成为一个问题. 。 这是一个改编自这个答案的解决方案:

 String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; List result = new ArrayList(); while(lastIndex != -1) { lastIndex = str.indexOf(findStr,lastIndex); if(lastIndex != -1){ result.add(lastIndex); lastIndex += 1; } }