Reputation: 1370
As the title says, I am looking to locate and count multiple matches of a target string within a larger string. For example:
# looking for
target <- "zoo"
# in this
word <- "zoozoo"
I have tried a few different things such as:
regexpr(target, word)
and
regmatches(word, regexpr(target, word))
But neither of these finds both of the substrings i.e. "zoo"
and "zoo"
. I am trying to write something that will find and count all of the matches, there will be multiple in what I am trying to do.
Your help is much appreciated.
Upvotes: 0
Views: 586
Reputation: 5530
If you need both the positions of the substrings and the count, you might try
positions <- unlist(gregexpr(target, word))
count <- length(positions)
Upvotes: 2
Reputation: 174706
You may use str_count
to count all the matched occurrences.
library(stringr)
str_count(word, target)
Upvotes: 3