Text <- c("instance", "percentage", "n",
"instance percentage", "percentage instance")
grepl("instance|percentage", Text)
# TRUE TRUE FALSE TRUE TRUE
grepl("instance.*percentage|percentage.*instance", Text)
# FALSE FALSE FALSE TRUE TRUE
后一种通过寻找:
('instance')(any character sequence)('percentage')
OR
('percentage')(any character sequence)('instance')
当然,如果您需要找到两个以上单词的任意组合,这将变得相当复杂。那么 cmets 中提到的解决方案会更容易实现和阅读。
匹配多个单词时可能相关的另一种替代方法是使用正向预测(可以被认为是“非消耗”匹配)。为此,您必须激活 perl 正则表达式。
# create a vector of word combinations
set.seed(1)
words <- c("instance", "percentage", "element",
"character", "n", "o", "p")
Text2 <- replicate(10, paste(sample(words, 5), collapse=" "))
# grepl with multiple positive look-ahead
longperl <- grepl("(?=.*instance)(?=.*percentage)(?=.*element)(?=.*character)",
Text2, perl=TRUE)
# this is equivalent to the solution proposed in the comments
longstrd <- grepl("instance", Text2) &
grepl("percentage", Text2) &
grepl("element", Text2) &
grepl("character", Text2)
# they produce identical results
identical(longperl, longstrd)
此外,如果您将模式存储在向量中,则可以显着压缩表达式,从而为您提供
pat <- c("instance", "percentage", "element", "character")
longperl <- grepl(paste0("(?=.*", pat, ")", collapse=""), Text2, perl=TRUE)
longstrd <- rowSums(sapply(pat, grepl, Text2) - 1L) == 0L
如 cmets 中所要求的,如果您想匹配确切的单词,即不匹配子字符串,我们可以使用 \\b 指定单词边界。例如:
tx <- c("cent element", "percentage element", "element cent", "element centimetre")
grepl("(?=.*\\bcent\\b)(?=.*element)", tx, perl=TRUE)
# TRUE FALSE TRUE FALSE
grepl("element", tx) & grepl("\\bcent\\b", tx)
# TRUE FALSE TRUE FALSE