i'm trying find occurrences of substring in string in java.
for example: searching "ababsdfasdfhelloasdf" "asdf" return [8,17] since there 2 "asdf"'s, 1 @ position 8 , 1 @ 17. searching "aaaaaa" "aa" return [0,1,2,3,4] because there "aa" @ positions 0,1,2,3, , 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 solved in python follows:
indices = [m.start() m in re.finditer(word, a.lower())]
where "word" word i'm looking , "a" string i'm searching through.
how can achieve in java?
you can use capturing inside positive look-ahead overlapping matches , use matcher#start
indices of captured substrings.
as the regex, 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
Comments
Post a Comment