This question already has answers here:
Remove all punctuation except apostrophes in R

(4个答案)


7年前关闭。





我正在尝试从字符串中删除除撇号外的所有标点符号。这是我的exastr2
str2 <- "this doesn't not have an apostrophe,.!@#$%^&*()"
gsub("[[:punct:,^\\']]"," ", str2 )
# [1] "this doesn't not have an apostrophe,.!@#$%^&*()"


我究竟做错了什么?

最佳答案

可以使用“负超前断言”来消除任何撇号,甚至在对它们进行标点字符测试之前也可以将其忽略掉。

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

07-24 09:22