2013-04-23 21 views
7

もっと効率的な方法がありますか? stringrなしでどうすればいいですか?文字ベクトル内の2つの特定の単語間のすべての単語を抽出する

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" 

答えて

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 " 
+0

おかげで、私はあなたがこれまであなたの袖のようなものを持っているだろうと思って! – Ben

+0

私は好奇心のために、各行の前に '## 'を出力しているものを尋ねてもいいですか?私はここに少しはいるが、それを何が生産しているのか分からない。 – Ben

+0

自分の.Rprofileに出力の前に '##'を挿入してクリップボードにコピーする手作りの機能があります。 –

1

ここで別のラフですを使って試してみてください、それはおそらくさらに洗練することができますけれども:

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

#[1] " and "    " goes with "   " is a long way from " 
関連する問題