我有一个字符串,我想删除所有非字母数字符号,然后放入一个矢量。所以这个:
"This is a string. In addition, this is a string!"
会变成:
>stringVector1
"This","is","a","string","In","addition","this","is","a","string"
我查看了grep()
,但找不到匹配的示例。有什么建议吗?
答案 0 :(得分:30)
这是一个例子:
> 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"
答案 1 :(得分:2)
处理此问题的另一种方法
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()
:将字符串分成多段