从字符串中删除非字母数字符号。

29
我有一个字符串,想要将其中所有非字母数字符号删除,并将其放入向量中。
所以,原本的字符串是这样的:
"This is a string.  In addition, this is a string!" 

将变成:

>stringVector1

"This","is","a","string","In","addition","this","is","a","string"

我查看了grep(),但找不到匹配的示例。 有什么建议吗?

2个回答

51

以下是一个例子:

> str <- "This is a string. In addition, this is a string!"
> str
[1] "This is a string. In addition, this is a string!"
> strsplit(gsub("[^[:alnum:] ]", "", str), " +")[[1]]
 [1] "This"     "is"       "a"        "string"   "In"       "addition" "this"     "is"       "a"       
[10] "string"  

我注意到正则表达式中在结束方括号之间有一个空格。这是用来做什么的? - B.Mr.W.
1
@B.Mr.W. 它保留了字符串中要分割的空格。 - mlegge
3
谢谢,终于我不害羞地在R中使用正则表达式了。gsub("[^[:alnum:]=\\.]", "", " Oh blah blah blah. Just be quiet!= 0.42 ") 比累加多次使用 gsub() 函数来将每个标点符号替换为 "" 要好得多。 - Paul Rougieux

5

另一种应对这个问题的方法

library(stringr)
text =  c("This is a string.  In addition, this is a string!")
str_split(str_squish((str_replace_all(text, regex("\\W+"), " "))), " ")
#[1] "This"     "is"       "a"        "string"   "In"       "addition" "this"     "is"       "a"        "string"  
  • str_replace_all(text, regex("\\W+"), " "): 查找非单词字符并替换为 " "
  • str_squish(): 压缩字符串中重复的空格
  • str_split(): 将字符串拆分成多个部分

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