如何测试两个字符串是否同时出现在另一个字符串中?

时间:2016-06-05 02:15:46

标签: regex r

为了测试一个模式是否出现在字符串中,我找到了这个函数(R):

grepl(pattern,string)

现在我想为模式指定更多特征:

  • OR:可以执行“pattern 1 | pattern 2”
  • AND:是否可以测试“模式1&模式2”是否都出现?我测试过,这个表达不起作用
  • 另外,如果我想要“(a | b)& c”等,

例如:

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

2 个答案:

答案 0 :(得分:3)

如果你只有很少的模式' (例如," t"和" e");您只需执行此操作即可测试是否所有这些都在字符串中(例如," test")。

grepl("t","test") & grepl("e","test")#TRUE

功能' str_detect'在包中' stringr'做同样的事情。

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

答案 1 :(得分:0)

如果要测试的模式很多,可以创建一个值来保存所有替代项,然后使用grepl搜索其中任何一个。这可以使许多变体更具可读性。

alt_strings <- c("t|e|z|123|friday|hello")
grepl(alt_strings,"test") #TRUE
grepl(alt_strings,"love fridays") #TRUE
grepl(alt_strings,"mondays sucks") #FALSE

如果要组合的逻辑AND和OR语句列表很长,可以使用grepl生成的逻辑向量的加法和乘法来跟踪事物。

#Equivalent to 4 OR statements
grepl(pattern,x) + grepl(pattern,x) + grepl(pattern,x) + grepl(pattern,x) >= 1

#Equivalent to 4 AND statements
grepl(pattern,x) * grepl(pattern,x) * grepl(pattern,x) * grepl(pattern,x) >= 1

#Mix of 3 OR and 1 AND
(grepl(pattern,x) + grepl(pattern,x) + grepl(pattern,x)) * grepl(pattern,x) >= 1