2016-07-13 30 views
5

使用grep以任意順序匹配多個模式的最短途徑是什麼?優選在一條短線中使用基線R.以任意順序在字符串中的任意位置匹配多個模式

下面是一個例子:

我想找到包含所有元素所有matches矢量這兩種元素,在任何順序,在在一起的my_vector元素的任何位置,元素之間有任何字符。

matches <- c("fe", "ve") 

#    1 2 3  4  5  6  7  8  9 
my_vector <- c("fv", "v", "f", "f_v_e", "fe_ve", "feve", "vefe", "fve" , "a") 

# want 5, 6, 7 

我可以這樣做:

grep(paste0("(?=.*", paste0(matches, sep = ""), ")", collapse = ""), 
    my_vector, 
    perl = TRUE) 

[1] 5 6 7 

但有一個更簡潔的方法?在我的例子中,我有兩個元素可以匹配,但是我的實際問題有幾個。

+0

@ user2100721 - 哪裏是「fe」在8? – thelatemail

+1

@ user2100721 - *我想查找包含這兩個元素的所有**的所有元素* – thelatemail

+1

@thelatemail:哦......對不起。我錯過了。謝謝。 – user2100721

回答

4

一個選項,以避免regex/paste

which(grepl(matches[1], my_vector) & grepl(matches[2],my_vector)) 
#[1] 5 6 7 

爲了讓更多的動態

which(Reduce(`&`, lapply(matches, grepl, my_vector))) 
#[1] 5 6 7 

或者作爲@Jota提到grep可用於intersect

Reduce(intersect, lapply(matches, grep, my_vector)) 

如果有在matches,01中有很多元素方法可能無法正常工作...

+1

太棒了,謝謝!這樣可以減少輸入 – Ben

+5

類似地:'Reduce(intersect,lapply(matches,grep,my_vector))' – Jota

+1

用於管道:'my_df%>%filter(Reduce('&',lapply(matches,grepl,my_column )))''反引號(&不知道如何在評論中得到它!) – Ben

相關問題