簡體   English   中英

在 R 中查找多個字符串內匹配項

[英]finding multiple within-string matches in R

正如標題所說,我希望在更大的字符串中定位和計算目標字符串的多個匹配項。 例如:

# looking for 
target <- "zoo"
# in this
word <- "zoozoo"

我嘗試了一些不同的事情,例如:

regexpr(target, word)

regmatches(word, regexpr(target, word))

但是這些都沒有找到兩個子字符串,即"zoo""zoo" 我正在嘗試寫一些可以找到並計算所有匹配項的東西,我正在嘗試做的事情會有多個。

非常感謝您的幫助。

您可以使用str_count來計算所有匹配的出現次數。

library(stringr)
str_count(word, target)

如果您需要子字符串的位置和計數,您可以嘗試

positions <- unlist(gregexpr(target, word))
count <- length(positions)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM