I have this string
x = "Hello how are you Peter /"
And I would like to get only
x = "Peter"
I would like to find patter that extract only word after "you" and before "/" (exluded)
I would like to use something like
x = sub(" you*/.", "", x)
But I dont know how to make the pattern correctly.
CodePudding user response:
gsub(".*you (.*) /$", "\\1", x)
CodePudding user response:
library(stringr)
str_match(x, "you\\s*(.*?)\\s*\\/")[, 2]
#[1] "Peter"
CodePudding user response:
With lookahead and lookbehind:
library(stringr)
x = "Hello how are you Peter /"
str_extract(x,"(?<=you )\\w (?= /)")
[1] "Peter"
If you want to be a bit more robust to spaces (if there is or not a space after the name for example, the example above will not work):
str_extract(x,"(?<=you)[\\w ] (?=/)") %>%
trimws()