如何选择包含单词的所有字符串恰好两个人?

时间:2018-04-05 08:15:20

标签: r

我的任务是:"选择所有包含恰好包含两个字的单词的字符串。"

我试过

grep("t{2}", text_strings, value = TRUE)

然而,它只选择包含两个t' s的字符串。

1 个答案:

答案 0 :(得分:0)

我们可以尝试

grep("\\b[^t]*t[^t]*t[^t]*\\b", text_strings, value = TRUE, ignore.case = TRUE)
#[1] "hotty" "total"

基于其他帖子中的示例

grep("\\b[^t]*t[^t]*t[^t]*\\b", V,  value = TRUE, ignore.case = TRUE)
#[1] "totally" "PotaTo"  "KiTten"  "ToTal"  

或另一个选项是str_count

library(stringr)
text_strings[str_count(text_strings, "t")==2]

和另一个例子

V[str_count(V, "[Tt]")==2]
#[1] "totally" "PotaTo"  "KiTten"  "ToTal"  

stringir

library(stringi)
text_strings[stri_count_fixed(text_strings, "t")==2]

数据

text_strings <- c("hotly", "hotty", "total", "hottyt")