florian florian - 1 year ago 98
R Question

How to remove multiple consecutive special characters in R?

How can I alter the following strings to not contain multiple consecutive question marks / other special characters in R?

"Nice one!!!"

should become

"Nice one!"



should become


I experimented with multiple regex commands without success. Obviously I can replace two question marks with one but I want it to be independent of the amount of special characters.

Answer Source

We can use gsub

gsub("([[:punct:]])\\1+", "\\1", str1)
#[1] "Nice one!" "Whazzup?!"


str1 <- c("Nice one!!!", "Whazzup????!!")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download