-1

Let's say this is my string

string<- c("righttoleftrightandleft")

I want to extract all the character between right and left so the result will be something like that

results<-("to","and")
Cyrus
  • 84,225
  • 14
  • 89
  • 153
Fouad Selmane
  • 378
  • 2
  • 11
  • This page may be of help: https://www.regular-expressions.info/rlanguage.html – Thomas Smyth - Treliant Jan 06 '18 at 23:46
  • What if there are two words in between left and right? Would the desired output of `lefttotherightand` be `[1] "tothe" "and"` or `[1] "to" "the" "and"`? Unsure how you would do the latter. – tyluRp Jan 07 '18 at 01:07

4 Answers4

4

Please try this with s <- "righttoleftrightandleft"

strsplit(gsub("right(.*?)left", "\\1 ", s), split="\\s")[[1]]

This gives a vector:

[1] "to"  "and"

Note that:

  1. gsub extracts all elements between parentheses, each stored in \\1
  2. ? is required for non-greedy match
  3. strsplit splits the resulting match on whitespace
Sun Bee
  • 1,595
  • 15
  • 22
3

Could try:

gsub("right(.*?)left", "\\1", regmatches(string, gregexpr("right(.*?)left",string))[[1]])

Where regmatches(...) returns matches sequences and gsub(...) extracts the word in the middle.

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
3

You can also use the following:

text="righttoleftrightandleft"
A=unlist(strsplit(text,"right|left",))
A[A!=""]
[1] "to"  "and"
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1
string<- c("righttoleftrightandleft")
vec <- strsplit(string, split = "left")

result <- c( sub(pattern = "right", "", vec[[1]][1:2]) )
AofWessex
  • 157
  • 11