Search code examples
rregexstringrstringi

Replace backslash to double backslash in special character


How can I replace the backslash in "\u2655" (greater equal sign) to "\\u2655"?

I've tried the following:

str_replace_all("\u2265", "\\\\", "\\\\\\")
stri_replace_all_fixed("\u2265", "\\", "\\\\")

Both lead to "≥" which is not "\u2265".


Solution

  • We interpret the problem as having an input character string containing unicode and we want to show the unicode as escaped symbols instead.

    Use

    stringi::stri_escape_unicode(x)
    

    For example if x is a single unicode character then this will give a 6 character string whose first character is backslash, second is u and next 4 are digits.

    x <- "\u2265"
    
    nchar(x)
    ## [1] 1
    
    cat(x, "\n")
    ## ≥
    
    y <- stringi::stri_escape_unicode(x)
    
    nchar(y)
    ## [1] 6
    
    cat(y, "\n")
    ## \u2265