はR

2017-01-05 11 views
-2

で部分文字列を抽出するために、どのように私は私が言葉「すべての」の後に2つの単語を抽出したいはR

x <- "Supplier will initially respond to High Priority incidents. Supplier will subsequently update EY every 60 minutes or at an interval EY specifies. Reporting and Response times will be capture in ServiceNow which, save in respect of manifest error, will be conclusive proof of the time period taken." 

以下のような文字列を持っています。

これはRでどのように達成できますか?

+0

matchを使用することができます示唆し '私にいくつかのcode'を与えます。 [ask]と[mcve]をお読みください。 – xenteros

答えて

3

我々は二つの単語

library(stringr) #corrected the package here 
unlist(str_extract_all(x, "(?<=every\\s)(\\w+\\s+\\w+)")) 
#[1] "60 minutes" 

または基地Rにおけるこのようなbase R

regmatches(x, gregexpr("(?<=every\\s)(\\w+\\s+\\w+)", x, perl = TRUE))[[1]] 
#[1] "60 minutes" 
+1

akrun、正しいパッケージは 'stringr'ではない' stringi' –

+0

@akrun - 応答ありがとう。 stringrのunlistコマンドを "every 30 seconds"に変更する方法を教えてください。 – Arun

+1

このペーストを試してみてください。 (\\ w \ \ s \ \ w +) "))、sep =" ")' –

2

何か、

を用い、続いて正規表現の回避策( (?<=every\\s))を使用して str_extractを使用することができ

文字列のすべての単語を分割し、 n単語everyの出現インデックスを見つけて、その索引から次の2語を選択する。

wordsplit <- unlist(strsplit(x, " ", fixed = TRUE)) 
indx <- grep("\\bevery\\b", wordsplit) 
wordsplit[(indx+1):(indx +2)] 
#[1] "60"  "minutes" 

それとも@DavidArenburgとして

は、我々はまた、代わりにあなたは0・努力を示し、質問をするので、それはおそらくです grep

wordsplit[match("every", wordsplit) + 1:2]