regex str_extract_all未列出所有可能的匹配项(R,stringr)

3npbholx  于 2023-06-30  发布在  其他
关注(0)|答案(2)|浏览(89)

场景设置

我有这个字符串:

string <- "Apples/Bananas/Grapes/"

我试图找到所有可能的子字符串匹配这个列表:

pattern <- "Apples/Bananas/|Bananas/Grapes/|Grapes/|Grapes/Pears/"

预期输出为:

"Apples/Bananas/" "Bananas/Grapes/" "Grapes/"

我所尝试的

使用str_extract_all:

matches <- str_extract_all(string, pattern)

但我只得到

"Apples/Bananas/" "Grapes/"

为什么不返回“香蕉/葡萄/"?

6gpjuf90

6gpjuf901#

尝试使用要提取的字符串向量:

library(stringr)

string <- "Apples/Bananas/Grapes/"

pattern <- c("Apples/Bananas/", "Bananas/Grapes/", "Grapes/", "Grapes/Pears/")

unlist(str_match_all(string, pattern))

#> [1] "Apples/Bananas/" "Bananas/Grapes/" "Grapes/"

创建于2023-06-28带有reprex v2.0.2

toiithl6

toiithl62#

使用strsplitstr_extract_all与原始字符串

library(stringr)

unlist(str_extract_all(string, unlist(strsplit(pattern, "\\|"))))
[1] "Apples/Bananas/" "Bananas/Grapes/" "Grapes/"

相关问题