R如何拆分字符串

时间:2017-04-10 07:14:54

标签: r regex string gsub

我有一个像

这样的字符串
a <- "Hi. I m cool, but I need help!"

作为我想要的输出

"hi" "." "I" "m" "cool" "," "but" "I" "need" "help" "!"

此外,我不想使用额外的包。

1 个答案:

答案 0 :(得分:1)

我们可以使用strsplit

a1 <- strsplit(a, '\\s|(?=[!,.])\\s*', perl = TRUE)[[1]]
a1[nzchar(a1)]
#[1] "Hi"   "."    "I"    "m"    "cool" ","    "but"  "I"    "need" "help" "!"