查找单词在字符串中的位置

Finding the position of a word in string

text = "the nurse was very helpful indeed"

我要搜索"very"然后提取"very"和"very"

后面的一个词

输出应该是:very helpful

我用过:

word(text, start = 4, end= 5 sep = fixed(" ")) 

这对提取很有帮助,但我无法动态获取字符串中单词位置的值,在这种情况下为“4”

我们可以使用 stringr

中的 str_extract
library(stringr)
str_extract(text, "very\s+\w+")

regexpr/regmatches 来自 base R

regmatches(text, regexpr("very\s+\w+", text))