R 中是否有相当于“匹配”函数的功能,可与正则表达式配合使用?

问题描述 投票:0回答:2

“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
2个回答
2
投票

使用

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

library(stringr)
sapply(Corpus, \(x) str_which(x, Lexicon))

# $animalada
# [1] 1
# 
# $fe
# [1] 3
# 
# $fernandez
# [1] 2 3
# 
# $ladrillo
# [1] 4

0
投票

跟进@Maël的回答,如果您需要返回Lexicon的实际值,这里有一个有用的习惯用法(假设两个列表之间的关系是一对一的:

library(stringr)
Lexicon[sapply(Corpus, \(x) str_which(x, Lexicon))]
© www.soinside.com 2019 - 2024. All rights reserved.