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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13985215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:46:06  来源:igfitidea点击:

replace special characters along with the space in list of strings

stringrspecial-characterswhitespace

提问by user1021713

I have character vector of strings like this :

我有这样的字符串字符向量:

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

I want to replace all the special characters and space and replace them with "_". I used str_replace allfrom the stringr packagelike this :

我想替换所有特殊字符和空格并用“_”替换它们。我用str_replace allstringr package这样的:

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"

Thanks for any help.

谢谢你的帮助。

采纳答案by Abin Manathoor Devasia

try this .

尝试这个 。

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

I don't have knowledge in R , i suggested the answer based on Regular expression checked withWiki

我没有 R 方面的知识,我建议基于使用Wiki检查的正则表达式的答案

回答by agstudy

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

"weather_is_good_today"  "it__will_rain_tomorrow" "do_not__get_angry"