2015-07-10 20 views
0

我想提取準備和營養\ nPer服務之間的內容。 我使用 -Gsub提取兩行之間的相關內容

gsub(".*\nPreparation\n\\s*|Tips & Notes*", "", filename) 

我的文件名看起來像

\nPreparation\nThinly slice both lemons and one orange. Combine the 
    sliced fruit with rum in a bowl. Cover and let macerate at least 8 hours 
or overnight.\nCombine sugar and water in a small saucepan; bring to a boil. Remove from the heat and stir in tea; let steep for 20 to 30 minutes. Strain into the rum mixture. Cover and chill.\nJust before serving, slice the remaining orange. Strain the rum mixture into a large punch bowl. Add Champagne or sparkling wine and seltzer. Float the orange slices in the punch.\nTips & Notes\nMake Ahead Tip: Prepare through Step 2. Cover and refrigerate for up to 3 days.\nNutrition\nPer serving 

回答

3

如果你想提取內容時,最好使用str_extractregmatches功能。

> regmatches(x, gregexpr("(?s)Preparation\\s*\\K.*?(?=\\s*\\bNutrition\\nPer serving)", x, perl=T))[[1]] 
[1] "Thinly slice both lemons and one orange. Combine the \n  sliced fruit with rum in a bowl. Cover and let macerate at least 8 hours \n or overnight.\nCombine sugar and water in a small saucepan; bring to a boil. Remove from the heat and stir in tea; let steep for 20 to 30 minutes. Strain into the rum mixture. Cover and chill.\nJust before serving, slice the remaining orange. Strain the rum mixture into a large punch bowl. Add Champagne or sparkling wine and seltzer. Float the orange slices in the punch.\nTips & Notes\nMake Ahead Tip: Prepare through Step 2. Cover and refrigerate for up to 3 days." 
+0

嘿Avinash你能分享一個鏈接,我可以從哪裏學習Regex – user459

+1

這裏http://www.regular-expressions.info/ –