Reputation: 3376
I want to replace the wild characters with the same character but with \
prefix.
For example:
gsub("#","\\#","234254#3")
Expected result: 234254\#3
but we get:
"234254#3"
gsub(" ","\\ ","234254 3")
Expected result: 234254\ 3
but we get:
"234254 3"
But this commands does not work.
Upvotes: 2
Views: 86
Reputation: 887213
You can use
res <- gsub("#","\\\\#","234254#3")
cat(res, '\n')
#234254\#3
nchar(res)
#[1] 9
To make it more clear
nchar('\\')
#[1] 1
For the second one also, it is the same \\\\
gsub(" ","\\\\ ","234254 3")
Upvotes: 3
Reputation: 785276
You can use fixed=TRUE
as 4th parameter of gsub
and use \\
in replacement:
res <- gsub("#", "\\#", "234254#3", fixed=TRUE)
cat(res)
Output:
234254\#3
Upvotes: 5