When using str_match, how to get output matrix column without the starting string?

Viewed 46

I am using str_match in R to extract values between start and end strings. For example, my code looks like this:

str_match("xxxxxBeginning Middle Endxxxxxxxx","(Beginning.+?)End")[,2]

This currently outputs Beginning Middle. How do I get an output of just Middle alone, without Beginning?

2 Answers

We can use a regex lookaround

str_match("xxxxxBeginning Middle Endxxxxxxxx","(?<=Beginning ).*(?= End)")[,1]
[1] "Middle"

Just put the brackets around the part you want to extract.

stringr::str_match("xxxxxBeginning Middle Endxxxxxxxx","Beginning (.+?) End")[,2]
#[1] "Middle"
Related