Search code examples
rstringi

Replace or remove multiple backslashes with 1 printed pair


How can I replace multiple backslashes with a single one? I know that in a string a single backslash is represented with \\ as demonstrated here:

nchar('\\')
[1] 1

So I want to replace replace all the backslashes in this string: 'thre\\\\fd' with one (prints as two) and when wrapped with cat will produce: thre\fd. I thought the stringi package has a way to do this easily but can't figure out how.

MWE (not correct output)

cat(gsub('\\\\', '\\', 'thre\\\\fd'))
## threfd

Desired Catted Output

thre\fd

Solution

  • Using the fixed = TRUE argument, we get

    cat(gsub('\\\\', '\\', 'thre\\\\fd', fixed = TRUE), '\n')
    #thre\fd 
    
    cat(gsub('\\\\\\', '\\\\', 'thre\\\\\\fd', fixed = TRUE), '\n')
    #thre\\fd