【问题标题】:is there an equivalent of the 'match' function in R, that works with regex?R 中是否有与 regex 一起使用的 \'match\' 函数的等价物?
【发布时间】:2022-11-30 17:18:33
【问题描述】:

'match' 的优势,它从词典中返回匹配的索引 缺点它不接受正则表达式

Corpus<- c('animalada', 'fe', 'fernandez', 'ladrillo')
Lexicon<- c('animal', 'animalada', 'fe', 'fernandez', 'ladr', 'ladrillo')

Index <- match(Corpus, Lexicon)

match 返回字典的索引

Index
# [1] 2 3 4 6

Lexicon[Index]
# [1] "animalada" "fe" "fernandez" "ladrillo" 

我需要使用包含正则表达式的字典

Lexicon<- c('anima.+$', '.*ez$', '^fe.*$', 'ladr.*$')

问题“匹配”功能,不适用于正则表达式!

【问题讨论】:

  • 你想要什么输出?

标签: r regex dictionary match


【解决方案1】:

使用grep + sapply。请注意,一个正则表达式可以应用于多个值,因此列表。

sapply(Lexicon, grep, Corpus, value = TRUE)
# $`anima.+$`
# [1] "animalada"
# 
# $`.*ez$`
# [1] "fernandez"
# 
# $`^fe.*$`
# [1] "fe"        "fernandez"
# 
# $`ladr.*$`
# [1] "ladrillo"

pmatch

Lexicon<- c('anima', 'ez', 'fe', 'ladr')
pmatch(Lexicon, Corpus)
#[1]  1 NA  2  4

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2017-12-17
    • 2022-10-15
    • 1970-01-01
    • 2019-12-15
    • 2011-05-28
    • 2019-11-07
    • 2020-10-25
    • 2023-01-17
    相关资源
    最近更新 更多