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

Time:11-17

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?

CodePudding user response:

We can use a regex lookaround

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

CodePudding user response:

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

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