[英]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.