Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a string of words between two specific words in R [duplicate]

Tags:

regex

r

I have the following string : "PRODUCT colgate good but not goodOKAY"

I want to extract all the words between PRODUCT and OKAY

like image 883
gyaanseeker Avatar asked Sep 05 '25 10:09

gyaanseeker


1 Answers

This can be done with sub:

s <- "PRODUCT colgate good but not goodOKAY"
sub(".*PRODUCT *(.*?) *OKAY.*", "\\1", s)

giving:

[1] "colgate good but not good"

No packages are needed.

Here is a visualization of the regular expression:

.*PRODUCT *(.*?) *OKAY.*

Regular expression visualization

Debuggex Demo

like image 106
G. Grothendieck Avatar answered Sep 08 '25 03:09

G. Grothendieck