查找Java中字符串中所有出现的子字符串
我正在尝试查找Java字符串中所有出现的子字符串。
例如:在“ ababsdfasdfhelloasdf”中搜索“ asdf”将返回[8,17],因为有2个“ asdf”,一个在位置8,另一个在17。在“
aaaaaa”中搜索“ aa”将返回[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获取捕获的子字符串的索引。
至于正则表达式,它将看起来像
(?=(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演示
以上是 查找Java中字符串中所有出现的子字符串 的全部内容, 来源链接: utcz.com/qa/404155.html








