使用grepl搜索文本中的多个子字符串

时间:2014-10-11 21:44:43

标签: r regex grepl

我在R中使用grepl()来搜索我的文本中是否存在以下任一类型。我现在这样做:

grepl("Action", my_text) |
grepl("Adventure", my_text) |  
grepl("Animation", my_text) |    
grepl("Biography", my_text) |  
grepl("Comedy", my_text) |    
grepl("Crime", my_text) |  
grepl("Documentary", my_text) |  
grepl("Drama", my_text) |  
grepl("Family", my_text) |  
grepl("Fantasy", my_text) |  
grepl("Film-Noir", my_text) |  
grepl("History", my_text) |  
grepl("Horror", my_text) |  
grepl("Music", my_text) |  
grepl("Musical", my_text) |  
grepl("Mystery", my_text) |  
grepl("Romance", my_text) |  
grepl("Sci-Fi", my_text) |  
grepl("Sport", my_text) |  
grepl("Thriller", my_text) |  
grepl("War", my_text) |    
grepl("Western", my_text) 

有没有更好的方法来编写此代码?我可以将所有类型放在一个数组中,然后以某种方式使用grepl()吗?

2 个答案:

答案 0 :(得分:29)

您可以将类型与“或”|分隔符粘贴在一起,然后通过grepl作为单个正则表达式运行。

x <- c("Action", "Adventure", "Animation", ...)
grepl(paste(x, collapse = "|"), my_text)

这是一个例子。

x <- c("Action", "Adventure", "Animation")
my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.")
grepl(paste(x, collapse = "|"), my_text)
# [1]  TRUE FALSE  TRUE

答案 1 :(得分:2)

您可以循环播放列表或类型向量,如下所示:

genres <- c("Action",...,"Western")
sapply(genres, function(x) grepl(x, my_text))

要回答您的问题,如果您只想知道结果的any元素是否为TRUE,您可以使用any()函数。

any(sapply(genres, function(x) grepl(x, my_text)))

很简单,如果任何元素为TRUE,any将返回TRUE。