Home > database >  Extract strings in R
Extract strings in R

Time:07-02

Is there a way to extract specific strings in R sentence. Example, I need only "test model" (What is there before 1st Commnents :). Is you see carefully, before "Commnents :", there is also "Comments are useful. " but I do not see. Just that what is there before 1st Commnents : is what I require

asd <- "Model : test modelComments : Comments are useful. Comments :"

Expected output

test model

Example 2

asd1 <- "Model : Example2Comments : Useful. Comments :"

Expected output

Example2

CodePudding user response:

How about

gsub(".*?: ([^:]*)Comments :.*", "\\1", asd)
# [1] "test model"

This grabs the non-colon values before the first "Comments :" appearance in the string. We capture the value and then replace the existing value with that matching group.

CodePudding user response:

You can use the following which matches anything between two strings:

asd <- "Model : test modelComments : Comments are useful. Comments :"
asd1 <- "Model : Example2Comments : Useful. Comments :"
library(stringr)
output <- str_match(asd, "Model : \\s*(.*?)\\s*Comments")
output[,2]
#> [1] "test model"
output1 <- str_match(asd1, "Model : \\s*(.*?)\\s*Comments")
output1[,2]
#> [1] "Example2"

Created on 2022-07-01 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related