正则表达式去除所有标点符号,除了撇号。

7

我正在尝试从字符串中删除所有标点符号,但保留撇号。以下是我的exastr2 -

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

我做错了什么?

我正在将标题不好的同一个问题链接在一起:https://dev59.com/SGoy5IYBdhLWcg3wN7e8 - Tyler Rinker
3个回答

17
"

负向先行断言"可用于排除任何撇号,甚至在测试其是否为标点符号之前。

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

当然,如果两个撇号相邻,则不会删除。但我猜你已经知道了。 - Arun
2
顺便提一下,这里有一个链接,是我见过的最好的负向先行断言的简短解释。 - Josh O'Brien
你也可以使用"(?!')(?!:)[[:punct:]]"来排除撇号和冒号。 - Scott Kaiser

1
我不确定你是否可以像你所做的那样在正则表达式中指定除'之外的所有标点符号。我会使用否定来检查字母数字+'+空格
gsub("[^'[:lower:] ]", "", str2) # per Joshua's comment
# [1] "this doesn't not have an apostrophe"

这要看他想要什么。如果他只想保证获取字母,则你所写的最合适。但如果他真的只是想去除标点符号,那么显式地去除标点符号更安全。 - John Sobolewski
5
应该使用[[:lower:]]而不是[a-z],因为后者是与语言环境相关的。 - Joshua Ulrich

1
你可以使用:

str2 <- "this doesn't not have an apostrophe,.!@#$%^&*()"

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

Tyler,openNLP是一个“依赖”包,无法安装并显示警告信息“不适用于R 2.15.2,因此无法安装qdap”。有什么想法吗? - Arun
1
是的,请查看这个页面:http://trinker.github.com/qdap_install/installation。我假设你正在使用Mac操作系统。 - Tyler Rinker
你能告诉我这是否适用于你,或者我可以对安装说明进行哪些改进吗? - Tyler Rinker
1
泰勒,从链接来看,它非常有效。没有问题。 - Arun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接