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

Find all occurrences of substring in string in Java

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

例如: 在 "ababsdfasdfhelloasdf" 中搜索 "asdf" 会 return [8,17] 因为有 2 个 "asdf",一个在位置 8,一个在位置 17。 在 "aaaaaa" 中搜索 "aa" 会 return [0,1,2,3,4] 因为在位置 0、1、2、3 和 4 处有一个 "aa" .

我试过这个:

public List<Integer> findSubstrings(String inwords, String inword) {
    String copyOfWords = inwords;
    List<Integer> indicesOfWord = new ArrayList<Integer>();
    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 来获取捕获的子字符串的索引。

至于the regex,它看起来像

(?=(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 demo

使用正则表达式绝对是查找子字符串的过于繁重的解决方案,如果您的子字符串包含特殊的正则表达式字符,如 .,则问题尤其严重。这是改编自 this answer:

的解决方案
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
List<Integer> result = new ArrayList<Integer>();

while(lastIndex != -1) {

    lastIndex = str.indexOf(findStr,lastIndex);

    if(lastIndex != -1){
        result.add(lastIndex);
        lastIndex += 1;
    }
}