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 ie "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.
You may use str_count
to count all the matched occurrences.
library(stringr)
str_count(word, target)
If you need both the positions of the substrings and the count, you might try
positions <- unlist(gregexpr(target, word))
count <- length(positions)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.