Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 带有模式数组的正则表达式(在R中)_Arrays_Regex_R - Fatal编程技术网

Arrays 带有模式数组的正则表达式(在R中)

Arrays 带有模式数组的正则表达式(在R中),arrays,regex,r,Arrays,Regex,R,我想识别与模式数组匹配的字符串的所有元素。我该怎么做?我希望避免循环的笨拙,因为我希望结果与指定模式的顺序保持不变 下面是一个简单的(非工作)示例 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)

我想识别与模式数组匹配的字符串的所有元素。我该怎么做?我希望避免循环的笨拙,因为我希望结果与指定模式的顺序保持不变

下面是一个简单的(非工作)示例

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
以启用regexp中的
(?=…)
前瞻)。它应该也适用于更复杂的模式,请查看有关前瞻的详细信息

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))

search不久前,我编写了一个名为的函数,可按如下方式使用:

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

它的设计目的是发现东西,即使是无序的。因此,例如,“to”将与“goat”匹配。但不确定这是否是解决问题所需的行为。

预期结果是什么?您需要匹配的每个单词的元素吗?或者整个单词,如果它包含正则表达式?例如,%regex
中的
unlist(strsplit(words[1],“”))%显示
words[1]
中的字符3与
regex
中的两个字符中的一个匹配。我需要true或false,以便可以获取具有特定列名的矩阵行。
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