str_extract_all not listing all possible matches (R, stringr)

Setting the Scene

I have this string:

string <- "Apples/Bananas/Grapes/"

I am trying to find all possible substring matches with this list:

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

The expected output is:

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

What I have tried

I tried using str_extract_all:

matches <- str_extract_all(string, pattern)

but I am only getting

"Apples/Bananas/" "Grapes/" 

Why is it not returning "Bananas/Grapes/"?

>Solution :

Try with a vector of strings you want to extract:

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/"

Created on 2023-06-28 with reprex v2.0.2

Leave a Reply