str_extract: Extracting exactly nth word from a string

Viewed 6361

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"

5 Answers

str_split is sometimes a popular choice. Call the nth word using [1,2], which returns the second word, [1,3] for the third, and so forth.

library(stringr)

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

#Code
str_split(sen, boundary("word"), simplify = T)[1,2]
#> [1] "am"

Created on 2018-08-16 by the reprex package (v0.2.0).

Related