2014-02-22 144 views
5

我想從字符串中刪除字母,但保護特定字詞。這裏是一個例子:保護特定字詞,從字符串中刪除字母

my.string <- "Water the 12 gold marigolds please, but not the 45 trees!" 

desired.result <- "12 marigolds, 45 trees" 

我試了下面的代碼,這給了一個令人驚訝的結果。我認爲()會保護它所包含的內容。相反,恰恰相反發生了。只有()內的文字被刪除(加上!)。

gsub("(marigolds|trees)\\D", "", my.string) 

# [1] "Water the 12 gold please, but not the 45 " 

這裏是一個較長的字符串的例子:

my.string <- "Water the 12 gold marigolds please, but not the 45 trees!, The 7 orange marigolds are fine." 

desired.result <- "12 marigolds, 45 trees, 7 marigolds" 

gsub("(marigolds|trees)\\D", "", my.string) 

返回:

[1] "Water the 12 gold please, but not the 45 , The 7 orange are fine." 

謝謝你的任何建議。我更喜歡基於Rregex解決方案。

回答

2

的其他方式與捕獲組:

my.string <- "Water the 12 gold marigolds please, but not the 45 trees!, The 7 orange marigolds are fine." 
gsub("(?i)\\b(?:(marigolds|trees)|[a-z]+)\\b\\s*|[.?!]", "\\1", my.string, perl=TRUE) 
7

使用詞邊界,否定前瞻斷言。

> my.string <- "Water the 12 gold marigolds please, but not the 45 trees!" 
> gsub("\\b(?!marigolds\\b|trees\\b)[A-Za-z]+\\s*", "", my.string, perl=TRUE) 
[1] "12 marigolds , 45 trees!" 
> gsub("\\b(?!marigolds\\b|trees\\b)[A-Za-z]+\\s*|!", "", my.string, perl=TRUE) 
[1] "12 marigolds , 45 trees" 
+0

謝謝。我如何修改這個刪除第二個例子中的最後一個點? –

+0

@MarkMiller,你的意思是'!'?我更新了答案。 – falsetru

+1

我認爲這樣做:'gsub(「\\ b(?!marigolds \\ b | trees \\ b)[A-Za-z] + \\ s * | [!.]」,「」,my .string,perl = TRUE)' –