stevec
stevec

Reputation: 52258

Extract all strings between two other strings?

Question is exactly the same as how to extract a string from between two other strings, except for extracting all strings between the two other strings.

To use the a similar example as the original question, suppose we wish to extract GET_ME and GET_ME_TOO from the string

a <-" anything goes here, STR1 GET_ME STR2, anything goes here STR1 GET_ME_TOO STR2"
res <- str_match(a, "STR1 (.*?) STR2")
res[,2]
[1] "GET_ME"

This retrieves the first, but not second (or subsequent) occurrences

Question

How can we extract all strings between two other strings?

Upvotes: 1

Views: 71

Answers (1)

akrun
akrun

Reputation: 887048

We can use str_match_all

library(stringr)
str_match_all(a, "STR1 (.*?) STR2")
#[[1]]
#     [,1]                   [,2]        
#[1,] "STR1 GET_ME STR2"     "GET_ME"    
#[2,] "STR1 GET_ME_TOO STR2" "GET_ME_TOO"

Upvotes: 3

Related Questions