如何在R中的两个单词之间获取文本?

Ron*_*hah 10 string r

我试图在一个句子中的两个单词之间得到文本.
例如,句子是 -

x <-  "This is my first sentence"
Run Code Online (Sandbox Code Playgroud)

现在我想的文本Thisfirstis my.我曾尝试各种功能与R一样grep,grepl,pmatch,str_split.但是,我无法得到我想要的东西.

这是我最接近的gsub.

gsub(".*This\\s*|first*", "", x)
Run Code Online (Sandbox Code Playgroud)

它给出的输出是

 [1] "is my  sentence"
Run Code Online (Sandbox Code Playgroud)

实际上,我所需要的只是

[1] "is my"
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

hwn*_*wnd 11

使用另一种方法rm_betweenqdapRegex包.

library(qdapRegex)
rm_between(x, 'This', 'first', extract=TRUE)[[1]]
# [1] "is my"
Run Code Online (Sandbox Code Playgroud)


akr*_*run 8

你需要.*在"第一个"之后匹配零个或多个字符

 gsub('^.*This\\s*|\\s*first.*$', '', x)
 #[1] "is my"
Run Code Online (Sandbox Code Playgroud)


Wim*_*pel 7

由于这个问题被用作参考,我将添加一些可能的解决方案来构建一个完整的概述。两者都基于look-ahead/look-behind正则表达式模式。

基数R

regmatches( x, gregexpr("(?<=This ).*(?= first)", x, perl = TRUE ) )
Run Code Online (Sandbox Code Playgroud)

纵梁

stringr::str_extract_all( x, "(?<=This ).+(?= first)" )
Run Code Online (Sandbox Code Playgroud)