提取字符向量中两个特定单词之间的所有单词

时间:2013-04-23 05:23:45

标签: regex string r

有更有效的方法吗?如果没有stringr,我怎么能这样做?

txt <- "I want to extract the words between this and that, this goes with that, this is a long way from that"

library(stringr)
w_start <- "this"
w_end <- "that"
pattern <- paste0(w_start, "(.*?)", w_end)
wordsbetween <- unlist(str_extract_all(txt, pattern))
gsub("^\\s+|\\s+$", "", str_sub(wordsbetween, nchar(w_start)+1, -nchar(w_end)-1))
[1] "and"                "goes with"          "is a long way from"

2 个答案:

答案 0 :(得分:12)

这是我在qdap中使用的方法:

使用qdap:

library(qdap)
genXtract(txt, "this", "that")

## > genXtract(txt, "this", "that")
##         this  :  that1         this  :  that2         this  :  that3 
##                " and "          " goes with " " is a long way from " 

没有添加套餐:

regmatches(txt, gregexpr("(?<=this).*?(?=that)", txt, perl=TRUE))

## > regmatches(txt, gregexpr("(?<=this).*?(?=that)", txt, perl=TRUE))
## [[1]]
## [1] " and "                " goes with "          " is a long way from "

答案 1 :(得分:1)

这是使用strsplit的另一个粗略尝试,尽管它可能会进一步改进:

txtspl <- unlist(strsplit(gsub("[[:punct:]]","",txt),"this|that"))
txtspl[txtspl!=" "][-1]

#[1] " and "                " goes with "          " is a long way from "