替换字符串列表中的特殊字符和空格

11

我有一个字符串的字符向量,就像这样:

x <- c("weather is good_today","it. will rain tomorrow","do not* get_angry")

我想要用 "_" 替换所有特殊字符和空格。 我使用了 stringr 包 中的 str_replace_all,代码如下:

x1 <- str_replace_all(x,"[[:punct:]]","_")
x2 <- str_replace_all(x1,"\\s+","_")

但是我能用一个命令完成这个操作,并且可以像这样获取输出吗:

But can this be done in one single command and I can get the output like this :

x
[1]"weather_is_good_today"
[2]"it_will_rain_tomorrow"
[3]"do_not_get_angry"

感谢任何帮助。


我可以问一下为什么您想要在一个命令中完成吗? - Tyler Rinker
@agstudy,请把它放回去。它本来就应该是一个答案。 - Tyler Rinker
2个回答

25
 gsub('([[:punct:]])|\\s+','_',x)

"weather_is_good_today"  "it__will_rain_tomorrow" "do_not__get_angry" 

4

试试这个。

x1 <- str_replace_all(x,"[[:punct:]\\\s]+","_")

我对R语言没有足够的了解,因此建议您根据维基百科提供的正则表达式来检查答案。


1
这个答案实际上是不准确的。虽然 "str_replace_all" 是一个很好的函数,但实际的正则表达式应该是 ([[:punct:]])|\s+)。 - Mike Williamson

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