Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_extract: Extracting exactly nth word from a string

I know this question has been asked at several places, but I didnt see a precise answer to this.

So I am trying to extract exactly the 2nd word from a string("trying to") in R with the help of regex. I do not want to use unlist(strsplit)

sen= "I am trying to substring here something, but I am not able to"

str_extract(sen, "trying to\\W*\\s+((?:\\S+\\s*){2})")

Ideally I want to get "here" as an output, but I am getting "trying to substring here"

like image 463
Manu Sharma Avatar asked Aug 02 '17 14:08

Manu Sharma


1 Answers

Since you also tagged stringr, I will post the word solution,

library(stringr)

word(sub('.*trying to ', '', sen), 2)
#[1] "here"
like image 96
Sotos Avatar answered Sep 19 '22 12:09

Sotos