Reputation: 224
I wanted to find the number of occurence of a substring in a string I implemented following code in java:
Pattern mypattern=Pattern.compile("a");
Matcher mymatcher=mypattern.compile("aaaaaa");
int cnt=0;
while(mymatcher.find()){
cnt++;
)
System.out.println(cnt);
But it doesn't work when I want the function to count also the intersecting strings for example I want th e answer to the search of aa in aaaaaa be 5 but the above program will show it 3.How can I do so?
Upvotes: 0
Views: 101
Reputation: 19575
A positive lookahead (?=(aa))
could be used in the regular expression to handle overlapping matches:
System.out.println(Pattern.compile("(?=(aa))").matcher("aaaaaa").results().count());
// 5
Upvotes: 1
Reputation: 566
You can use Apache Commons Lang library:
System.out.println(StringUtils.countMatches(str, subStr));
Upvotes: 0
Reputation: 20924
This code will give you your desired count of 5 if you are searching for occurrences of aa in aaaaaa.
Pattern mypattern = Pattern.compile("aa");
Matcher mymatcher = mypattern.matcher("aaaaaa");
int cnt = 0;
int start = 0;
while (mymatcher.find(start)) {
start = mymatcher.start() + 1;
cnt++;
}
System.out.println(cnt);
Upvotes: 1