gpt4 book ai didi

regex - 回复 grep : Match one string against multiple patterns

转载 作者:行者123 更新时间:2023-12-03 10:00:45 25 4
gpt4 key购买 nike

在 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

用“|”连接这么多关键字不是一种可行的方法(我不知道哪个关键字产生了命中)。
此外,仅仅颠倒“模式”和“字符串”是行不通的,因为模式有截断,反之则行不通。

[ related question , 其他编程语言]

最佳答案

将 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

返回的值是匹配中第一个字符的位置, -1意思是不匹配。

如果匹配的位置不相关,使用 grepl反而:
sapply(keywords, grepl, strings, ignore.case=TRUE)

dog cat bird
[1,] TRUE FALSE FALSE
[2,] FALSE TRUE TRUE
[3,] FALSE FALSE FALSE

更新:这在我的系统上运行速度相对较快,即使有大量关键字:
# 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

关于regex - 回复 grep : Match one string against multiple patterns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com