florian florian - 7 months ago 43
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.


We can use gsub

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


str1 <- c("Nice one!!!", "Whazzup????!!")