匹配两个字符串向量,忽略元素名称的顺序

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

下面,我想要

match()
两个字符串向量:我的
first
向量和我的
second1
向量,如下所示:

( desired_output = match(fisrt, second1) ) #> [1] 4 5 1 6 2 3

但是我的

second1
向量可以具有相反的两部分字符串元素,例如而不是
"perf.acog"
"acog.perf"
,如我的
second2
向量中所示。

问题: 我们能让

match(fisrt, second2)
产生与
match(fisrt, second1)
相同的输出吗?

注意: 两部分字符串元素可以通过

"[^[:alnum:]]+"
中定义的任何分隔符连接,例如
"."
(例如
"perf.acog"
)、
"_"
(例如
"perf_acog"
)等。 ,感谢一般/功能性答案。

first = c("asom.acog", "conf.acog", "perf.acog", "conf.asom", "perf.asom", 
          "perf.conf")

second1 = c("perf.acog", "perf.asom", "perf.conf", "asom.acog", "conf.acog", 
           "conf.asom")

second2 = c("acog.perf", "asom.perf", "conf.perf", "acog.asom", "acog.conf", 
            "asom.conf")
r regex string vector functional-programming
1个回答
0
投票

在字符串

rev
和非单词字符
strsplit
上使用
\\W

match(first, lapply(strsplit(second2, "\\W"), \(x) paste(rev(x), collapse=".")))
[1] 4 5 1 6 2 3
© www.soinside.com 2019 - 2024. All rights reserved.