[英]regular expression with an array of patterns (in R)
我想識別與模式數組匹配的字符串的所有元素。 我該怎么做呢? 我想避免笨拙的for循環,因為我希望結果不會改變指定模式的順序。
這是一個簡單的(無效)示例。
regex = c('a','b')
words = c('goat','sheep','banana','aardvark','cow','bird')
grepl(regex,words)
[1] TRUE FALSE TRUE TRUE FALSE FALSE
Warning message:
In grepl(regex, words) :
argument 'pattern' has length > 1 and only the first element will be used
編輯:對不起,意識到我之前已經看到了答案,只是忘記了它-可能是grepl('(a)|(b)',words)
,但是我需要一些強制方法排列成這種形式
使用sapply
:
> sapply(regex, grepl, words)
a b
[1,] TRUE FALSE
[2,] FALSE FALSE
[3,] TRUE TRUE
[4,] TRUE FALSE
[5,] FALSE FALSE
[6,] FALSE TRUE
最初的問題建議上述是所要的,但隨后更改為要求包含regex
任何元素的那些元素。 在這種情況下:
> grepl(paste(regex, collapse = "|"), words)
[1] TRUE FALSE TRUE TRUE FALSE TRUE
您可以提前在正則表達式中進行操作。 這是將搜索詞中的正則表達式拼接在一起的示例( a
和b
只應匹配banana
,請確保將perl = TRUE
設置為在正則表達式中啟用(?=...)
超前)。 它也應該適用於更復雜的模式,請查看本教程以獲取有關預讀的詳細信息。
search <- c('a','b')
words <- c('goat','sheep','banana','aardvark','cow','bird')
regex <- paste(paste0("(?=.*", search, ")"), collapse = "")
matches <- grepl(regex,words, perl = T)
print(data.frame(words, matches))
更新:這是針對匹配所有搜索詞的原始問題,可以如對原始問題的編輯中所述實現匹配任何搜索詞
needleInHaystack
,我編寫了一個名為needleInHaystack
的函數,該函數可以按如下方式使用:
x <- needleInHaystack(regex, words)
x
# a b
# goat 1 0
# sheep 0 0
# banana 1 1
# aardvark 1 0
# cow 0 0
# bird 0 1
根據如果你想對all
或any
,很容易使用的apply
(或rowSums
)。
apply(x, 1, function(x) any(as.logical(x)))
# goat sheep banana aardvark cow bird
# TRUE FALSE TRUE TRUE FALSE TRUE
apply(x, 1, function(x) all(as.logical(x)))
# goat sheep banana aardvark cow bird
# FALSE FALSE TRUE FALSE FALSE FALSE
它旨在發現混亂的事物。 因此,例如,“到”將匹配“山羊”。 不確定這是否是您想要解決的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.