为了测试模式是否出现在字符串中,我找到了以下函数(R):
grepl(pattern,string)
现在,我想为模式指定更多特征:
例子:
grepl("t","test") # returns TRUE OK
grepl("t|i","test") # returns TRUE OK
grepl("t&e","test") # I want to test if "t" and "e" are both in "test", which is TRUE
如果您只有很少的“模式”(例如,“ t”和“ e”);您只需执行此操作即可测试它们是否都在字符串中(例如,“ test”)。
grepl("t","test") & grepl("e","test")#TRUE
包“ stringr”中的函数“ str_detect”执行相同的操作。
library('stringr')
str_detect("test", "t") & str_detect("test", "e")#TRUE
您也可以编写自己的函数,如果您有很多模式,这可能会很方便。您可以通过许多不同的方式来执行此操作。这是一个例子。
library(stringr)
all_in <- function(string, patterns){
res1 <- NULL
for (i in 1:length(patterns)){
res1 <- rbind(res1, str_detect(string, patterns[i]))
}
res2 <- NULL
for (i in 1:NCOL(res1)){
res2 <- c(res2, all(res1[,i]))
}
res2
}
#test which elements of vector 'a' contain all elements in 'b'
a <- c("tea", "sugar", "peas", "tomato", "potatoe", "parsley", "tangelo")
b <- c("a", "e", "o", "t")
all_in(a,b)#FALSE FALSE FALSE FALSE TRUE FALSE TRUE
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句