Using vector in a regex to extract substrings with only known start & end

Viewed 90

How do you use a vector in a regular expression so you can extract everything from the the vector to another word?

I need to extract multiple substrings from a series of large strings in a dataframe using str_match. Each substring starts with a tree species and ends with the word "links". Since the substrings I need could start with a number of different species, I created a vector called tree.sp to contain all possibilities.

test.df <- data.frame(
  Heading_ChLk = c("West", 40.00, 80.00),
  Bound_Desc = c("On the Base line along the south side of section 34 T 1 N, R 29 W of the 5th PM.",
                 "Set a 1/4 section corner post from which a pine 9 inches diameter bears N 43 E 35 links and a black oak 15 inches diameter bears S 10 E 30 links",
                 "Set a post corner to sections 33 & 34 from which a white oak 17 inches diameter bears N 32 W 57 links and a black oak 20 inches diameter bears N 46 E 19 links.")
)

tree.sp <- c("pine|black oak|white oak")
1 Answers

You may use str_match as -

library(stringr)

test.df$result <- str_match(test.df$Bound_Desc, sprintf('((%s).*links)', tree.sp))[, 2]
test.df$result

#[1] NA                                                                                                           
#[2] "pine 9 inches diameter bears N 43 E 35 links and a black oak 15 inches diameter bears S 10 E 30 links"      
#[3] "white oak 17 inches diameter bears N 32 W 57 links and a black oak 20 inches diameter bears N 46 E 19 links"

Similar code can be used with str_extract as well -

str_extract(test.df$Bound_Desc, sprintf('(%s).*links', tree.sp))
Related