Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract substrings dynamically

Tags:

regex

r

From the string

s <- "|tree| Lorem ipsum dolor sit amet, |house| consectetur adipiscing elit, 
|street| sed do eiusmod tempor incididunt ut labore et |car| dolore magna aliqua."

I want to extract the text after the letters within the |-symbols.

My approach:

words <- list("tree","house","street","car")

for(word in words){
   expression <- paste0("^.*\\|",word,"\\|\\s*(.+?)\\s*\\|.*$")
   print(sub(expression, "\\1", s))
}

This works fine for all but the last wortd car. It instead returns the entire string s. How can I modify the regex such that for the last element of words-list in prints out dolore magna aliqua..

\Edit: Previously the list with expressions was a,b,c,d. Solutions to this specific problem cannot be generalized very well.

like image 216
volfi Avatar asked Sep 06 '26 07:09

volfi


1 Answers

Try this:

library(stringi)

s <- '|a| Lorem ipsum dolor sit amet, |b| consectetur adipiscing elit, 
|c| sed do eiusmod tempor incididunt ut labore et |d| dolore magna aliqua.'

stri_split_regex(s, '\\|[:alpha:]\\|')

[[1]]
[1] ""                                                " Lorem ipsum dolor sit amet, "                  
[3] " consectetur adipiscing elit, \n"                " sed do eiusmod tempor incididunt ut labore et "
[5] " dolore magna aliqua."     
like image 70
daniellga Avatar answered Sep 07 '26 21:09

daniellga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!