In R, how to use regex [:punct:] in gsub?

r, regex

Solution

Fellow MontReal user here.

Several options, sames results.

In R Base, just double the brackets

gsub(pattern="[[:punct:]]", test, replacement=" ")

[1] "Low Decarie  Etienne"

Package `stringr` has function `str_replace_all` that does that.

library(stringr)
str_replace_all(test, "[[:punct:]]", " ")

Or keep only letters

str_replace_all(test, "[^[:alnum:]]", " ")

Problem

Given ``` test<-"Low-Decarie, Etienne" ``` I wish to replace all punctuation with space ``` gsub(pattern="[:punct:]", x=test, replacement=" ") ``` but this produces ``` "Low-De arie, E ie e" ``` where no punctuation is replaced and apparently random letters are removed (though they may be associated with punctation as t for tab and n for next line).

Original source