2013-03-06 270 views
4

我試圖從字符串中除去撇號以外的所有標點符號。這裏是我的exastr2 < -R正則表達式除去撇號除外的所有標點符號

str2 <- "this doesn't not have an apostrophe,[email protected]#$%^&*()" 
gsub("[[:punct:,^\\']]"," ", str2) 
# [1] "this doesn't not have an apostrophe,[email protected]#$%^&*()" 

我在做什麼錯?

+0

我有一個壞的標題連接同一個問題:http://stackoverflow.com/questions/8697079/regex-exception-in-r – 2013-03-06 20:57:05

回答

13

A「式斷言」可用於以不考慮任何撇號刪除,他們甚至爲是標點字符測試之前。

gsub("(?!')[[:punct:]]", "", str2, perl=TRUE) 
# [1] "this doesn't not have an apostrophe" 
+0

這當然不會刪除,如果兩個撇號彼此相鄰。但我想你已經知道了。 – Arun 2013-03-06 19:12:02

+2

FWIW,[這裏是一個鏈接](http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word)對負面查找斷言的最佳簡短解釋,我見過。 – 2013-03-06 19:27:02

1

我不確定您是否可以按照您所做的方式在正則表達式中指定除'之外的所有標點符號。我會檢查alphanumerics + ' + space與否定:

gsub("[^'[:lower:] ]", "", str2) # per Joshua's comment 
# [1] "this doesn't not have an apostrophe" 
+0

它取決於他想要的。他是否想確保他只能得到信件,那麼你寫的是最合適的。如果他真的只想刪除標點符號,那麼明確刪除標點符號會更安全。 – 2013-03-06 19:02:53

+4

由於後者是特定於語言環境的,因此應該使用'[[:lower:]]'而不是'[a-z]'。 – 2013-03-06 19:08:48

1

你可以使用:

str2 <- "this doesn't not have an apostrophe,[email protected]#$%^&*()" 

library(qdap) 
strip(str2, apostrophe.remove = FALSE, lower.case = FALSE) 
+0

Tyler,openNLP「depends」包不會安裝並退出,並顯示警告消息「不適用於R 2.15.2,因此無法安裝'qdap'。任何想法? – Arun 2013-03-07 08:02:49

+1

是檢查此頁面:http:// trinker.github.com/qdap_install/installation。我假設你使用的是mac。 – 2013-03-07 13:03:03

+0

你可以告訴我iy是否適合你,或者我可以對安裝說明做出改進 – 2013-03-07 13:10:08

相關問題