Search code examples
stringrspecial-characterswhitespace

replace special characters along with the space in list of strings


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 all from the stringr package like this :

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.


Solution

  • 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