florian florian - 1 month ago 11
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!"


and

"Whazzup????!!"


should become

"Whazzup?!"


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

We can use gsub

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

data

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