1

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?

Community
  • 1
  • 1
stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

3

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"
akrun
  • 874,273
  • 37
  • 540
  • 662