在R中,grep通常匹配多个字符串的向量与一个正则表达式.
问:是否有可能将单个字符串与多个正则表达式匹配?(没有循环遍历每个单一的正则表达式模式)?
一些背景:
我有7000多个关键字作为几个类别的指标.我无法更改该关键字字典.字典具有以下结构(第1列中的关键字,数字表示这些关键字所属的类别):
ab 10 37 41
abbrach* 38
abbreche 39
abbrich* 39
abend* 37
abendessen* 60 63
aber 20 23 45
abermals 37
Run Code Online (Sandbox Code Playgroud)
用"|"连接这么多关键字 是不可行的方式(我不知道哪个关键字产生了命中).此外,只是反转"模式"和"字符串"不起作用,因为模式具有截断,这在其他方面不起作用.
[ 相关问题,其他编程语言]
dan*_*ota 32
将regexpr函数应用于关键字向量怎么样?
keywords <- c("dog", "cat", "bird")
strings <- c("Do you have a dog?", "My cat ate by bird.", "Let's get icecream!")
sapply(keywords, regexpr, strings, ignore.case=TRUE)
dog cat bird
[1,] 15 -1 -1
[2,] -1 4 15
[3,] -1 -1 -1
sapply(keywords, regexpr, strings[1], ignore.case=TRUE)
dog cat bird
15 -1 -1
Run Code Online (Sandbox Code Playgroud)
返回的值是匹配中第一个字符的位置,其-1含义不匹配.
如果匹配的位置无关紧要,请grepl改用:
sapply(keywords, grepl, strings, ignore.case=TRUE)
dog cat bird
[1,] TRUE FALSE FALSE
[2,] FALSE TRUE TRUE
[3,] FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
更新:即使有大量关键字,我的系统运行速度也相对较快:
# Available on most *nix systems
words <- scan("/usr/share/dict/words", what="")
length(words)
[1] 234936
system.time(matches <- sapply(words, grepl, strings, ignore.case=TRUE))
user system elapsed
7.495 0.155 7.596
dim(matches)
[1] 3 234936
Run Code Online (Sandbox Code Playgroud)