简体   繁体   English

在 R 中查找多个字符串内匹配项

[英]finding multiple within-string matches in R

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" .但是这些都没有找到两个子字符串,即"zoo""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.您可以使用str_count来计算所有匹配的出现次数。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM