A.Naskar A.Naskar - 1 month ago 7
R Question

How to get multiple text between two words in a string R?

I am trying to get the text between two words in a sentence.
For example the sentence is -

x <- "This is my first sentence and This is my second sentence"


Now I want output like :

[1] first second


This is what I have tried but its not working

gsub('^.*This is my \\s*|\\s*sentence.*$', '', x)

Answer

Try this:

x <-  "This is my first sentence and This is my second sentence"
gsub('.*?This is my (\\w*?) sentence.*?', '\\1 ', x)
Comments