Replace a pattern with special characters in R

Viewed 27

I have a string x as below. I am trying to replace "c("" and "\nLOC" such that I am left with only Abc,xyz.

x<-"c(\"Abc, xyz\\nLOC"

This is what I tried which works but is there a shorter way of doing it?

x <-str_replace_all(x, "[^[:alnum:]]", " ")
x <-str_replace_all(x, "c  ", "")
x <-str_replace_all(x, "nLOC", "")
1 Answers

With only a single example, it's hard to know what to generalize... You could do it all in one big pattern,

str_replace_all(x, "[^[:alnum:],]|^c|nLOC", "")
[1] "Abc,xyz"
Related