Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

regex - Find all occurrences of substring in string in Java

I'm trying to find all occurrences of a substring in a string in Java.

For example: searching "ababsdfasdfhelloasdf" for "asdf" would return [8,17] since there are 2 "asdf"'s, one at position 8 and one at 17. Searching "aaaaaa" for "aa" would return [0,1,2,3,4] because there is an "aa" at positions 0,1,2,3, and 4.

I tried this:

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);
    }

This problem can be solved in Python as follows:

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

where "word" is the word I'm looking for and "a" is the string I'm searching through.

How can I achieve this in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use capturing inside a positive look-ahead to get all overlapping matches and use Matcher#start to get the indices of the captured substrings.

As for the regex, it will look like

(?=(aa))

In Java code:

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);

Result:

[0, 1, 2, 3, 4]

See IDEONE demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...