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

Kev*_*vin 9 java regex string substring

我试图在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<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);
    }
Run Code Online (Sandbox Code Playgroud)

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

indices = [m.start() for m in re.finditer(word, a.lower())]
Run Code Online (Sandbox Code Playgroud)

"word"是我正在寻找的单词,"a"是我正在搜索的字符串.

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

Wik*_*żew 9

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

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

(?=(aa))
Run Code Online (Sandbox Code Playgroud)

在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);
Run Code Online (Sandbox Code Playgroud)

结果:

[0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

请参阅IDEONE演示


Ale*_*all 5

使用正则表达式对于查找子字符串来说绝对是一个过于繁重的解决方案,如果您的子字符串包含特殊的正则表达式字符(例如.. 这是根据此答案改编的解决方案:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)